我正在尝试使用以下代码在 Yahoo 中搜索查询:
import requests
from bs4 import BeautifulSoup
query = "deep"
yahoo = "https://search.yahoo.com/search?q=" + query + "&n=" + str(10)
raw_page = requests.get(yahoo)
soup = BeautifulSoup(raw_page.text)
for link in soup.find_all(attrs={"class": "ac-algo fz-l ac-21th lh-24"}):
print (link.text, link.get('href'))
但这不起作用,结果为空。我怎样才能获得 10 个第一个搜索结果?
以下是您的代码的主要问题:
使用 Beautiful 汤时,您应该始终包含一个解析器 (例如BeautifulSoup(raw_page.text, "lxml")
)
您正在搜索错误的课程,它" ac-algo fz-l ac-21th lh-24"
不是"ac-algo fz-l ac-21th lh-24"
(注意开头的空格)
总而言之,您的代码应如下所示:
import requests
from bs4 import BeautifulSoup
query = "deep"
yahoo = "https://search.yahoo.com/search?q=" + query + "&n=" + str(10)
raw_page = requests.get(yahoo)
soup = BeautifulSoup(raw_page.text, "lxml")
for link in soup.find_all(attrs={"class": " ac-algo fz-l ac-21th lh-24"}):
print(link.text, link.get('href'))
希望这可以帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句