Python Beautiful Soup - Getting input value

百般思念 提交于 2020-02-08 05:12:47

问题


My plan is to be able to grab the _AntiCsrfToken by using Bs4.

I have this HTML where my HTML comes from

and what I have written in the code is

token = soup.find('input', {'name':'_AntiCsrfToken'})['value'])
print(token)

but it gives me a error saying

    Traceback (most recent call last):
  File "C:\Users\HelloWorld.py", line 67, in <module>
    print(soup.find('input', {'name':'_AntiCsrfToken'})['value'])
  File "C:\Python\lib\site-packages\bs4\element.py", line 1292, in find
    l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
AttributeError: 'str' object has no attribute 'find_all'

I quite dont understand if I have done it right or not. I do think I did it right but maybe I need to find it before from form-id than just go into hidden directly ?


回答1:


I am not sure where the error lies for you but I have made a little html file and put it on my server and I have no problem copying and pasting your code..

The only noticeable difference (if you have not done it) is that I am using requests to parse the html to BS4

I think maybe it is a parsing problem.

HTML

<html>

<form action="process">
<input type="hidden" name="_AntiCsrfToken" value="5435434354353453545">

</form>
</html>

Python:

from bs4 import BeautifulSoup as bs4
import requests

r = requests.get('http://maffaz.com/so.html')
html_bytes = r.text
soup = bs4(html_bytes, 'lxml')
token = soup.find('input', {'name':'_AntiCsrfToken'})['value']
print(token)

returns:

5435434354353453545

Also you do not need

{'name':'_AntiCsrfToken'}

so:

token = soup.find('input')['value']

Will work




回答2:


Maybe try using CSS selectors?

from bs4 import BeautifulSoup

html = """
<html>
<input type="hidden" name="_AntiCsrfToken" value="5435434354353453545">
</html>
"""

soup = BeautifulSoup(html, 'lxml')
csrf = soup.select_one('input[name=_AntiCsrfToken]')['value']
print(csrf)

Output: 5435434354353453545



来源:https://stackoverflow.com/questions/46028156/python-beautiful-soup-getting-input-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!