【发布时间】:2021-04-20 04:46:01
【问题描述】:
我正在尝试获取页面的 html,但它显示为列表的第二个值↓。
Traceback (most recent call last):
File "E:\mycodes\python codes\testcode.py", line 14, in <module>
print(soup.prettify())
File "C:\Users\sonug\AppData\Local\Programs\Python\Python36-32\lib\site-packages\bs4\element.py", line 2161, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'prettify'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
它成功打印了第一页的 html 代码,只是没有打印列表的第二个值。
这是我的代码:-
from bs4 import BeautifulSoup as soup
import requests
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"
session = requests.Session()
session.headers['User-Agent'] = USER_AGENT
query=['who is the president of India','who is the president of usa']
for query in query:
url=f"https://www.google.com/search?q={query}"
html = session.get(url).text
soup = soup(html,'html.parser')
print(soup.prettify())
【问题讨论】:
-
把你的变量名改成其他的!
result = soup(html,'html.parser')
标签: python beautifulsoup python-requests