我正在try 使用BeautifulSoup来查找不同作者的出生年份.我在VS Code工作,如果这是相关的话.这是我第一次try 抓取网页,所以请尽量解释清楚
对于有维基百科页面的作者,我可以使用以下代码成功地找到出生年份:
source_code = requests.get("a_wikipedia_url")
plain_text = source_code.text
soup = BeautifulSoup(plain_text, features="html.parser")
finder = soup.find("span", {"class": "bday"})
if finder is not None:
birth_year = finder.string[0:4]
return birth_year
然而,当我用谷歌搜索没有(英文)维基百科页面的作者时,我什么也得不到.
在阅读了这个问题https://stackoverflow.com/questions/62466340/cant-scrape-google-search-results-with-beautifulsoup之后,我向quests.get(我使用的是Chrome版本114.0.5735.134(官方版本)(64位)和Windows 11 Home)添加了一个用户代理响应头,但它所做的只是打印None,而不是给我的AttributeError:‘NoneType’对象没有‘字符串’属性,这是我在添加头之前得到的.
这是我的代码:
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.134 Safari/537.36"}
source_code = requests.get("https://www.google.com/search?q=Guillermo+Saccomanno", headers=headers)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, features="html.parser")
google_finder = soup.find("span", {"class": "LrzXr kno-fv wHYlTd z8gr9e"})
print(google_finder.string)
结果就是无--没有错误消息,但没有文本.
我还try 了标题Chrome Version为Chrome/114.0.0.0,这是我在网上找到的.还是什么都不给.
我不确定我错在哪里,因为语法是相同的,而且我从页面源代码复制了类名?对于这位特定的作者,我认为google_finder.string应该是"1948年6月9日(75岁)".