使用 Python 进行网络抓取,当我说检查页面时,我看不到类的实际名称



好的,所以我只是在学习python,我想使用web抓取。我在看这个教程,导师有一个与我完全不同的"检查"页面(或其他名称(。所以他看到的是class="ProfileHeaderCard",而我看到的是class="css-1dbjc4n r-1iusvr4 r-16y2uox r-5f2r5o r-m611by"。重要的是,当我使用类名的版本时,BeautifulSoup库不起作用,但当我使用他的版本时,它起作用。当我说print(soup.find('div', {"class":"css-1dbjc4n r-1iusvr4 r-16y2uox r-5f2r5o r-m611by"}))它返回None发生了什么事,哈哈,请帮忙。

from bs4 import BeautifulSoup
import urllib.request
theurl = 'https://twitter.com/1kasecorba'
thepage = urllib.request.urlopen(theurl)
soup = BeautifulSoup(thepage, 'html.parser')
print(soup.find('div', {"class":"css-1dbjc4n r-1iusvr4 r-16y2uox r-5f2r5o r-m611by"}))

它找不到它,因为它不在那里。请注意,当您在页面上执行GET请求时,您通常不会得到在浏览器中打开页面并在那里看到源时看到的相同源(Control+U(。

我写了一个脚本,将urllib获得的源代码的内容写入一个文本文件,但没有这样的类。soup.find函数没有任何问题,正如您将在最后一行的示例中看到的那样。

from bs4 import BeautifulSoup
import urllib.request
theurl = 'https://twitter.com/1kasecorba'
thepage = urllib.request.urlopen(theurl)
soup = BeautifulSoup(thepage, 'html.parser')
file = open("page_source.txt", "w+", encoding="utf-8")
file.write(str(soup))
file.close()
# works as charm
print(soup.find('button', {"class":"modal-btn modal-close modal-close-fixed js-close"}))

如果你想看到真正的来源,你需要一个像Selenium这样的工具(可能有更好的选择,我不能就这个话题给出太多建议(。

最新更新