首页 > 解决方案 > 如何抓取嵌套的 div 和 ol 类

问题描述

我正在尝试抓取此网页

我希望从“照片流容器”下载一些照片,但没有任何成功。下面是我目前正在使用的代码块。

寻找以“自适应”开头的所有跨度类作为示例类将是“AdaptiveStreamGridImage grid-tweet has-cards has-content enabled clear first-row hoverZoomLink”

有什么建议吗?

d = requests.get('https://twitter.com/search?f=images&vertical=news&q=Iran').text
soup = BeautifulSoup(d, 'html.parser')

spans = soup.findAll("span", {"class": lambda x: x and x.startswith('Adaptive')})
print(spans)

打印“跨度”时收到一个空列表

[]

标签: pythonhtmlweb-scrapingtwitterbeautifulsoup

解决方案


您想要的内容很可能被 JS 脚本的力量所隐藏。我们的request库不会打扰那些 JS 脚本,它会获取在您的浏览器的 JS less 模式下对您可见的内容。这个问题可以在selenium图书馆的帮助下解决。它允许您加载您的网页及其内容,就像您使用的任何其他浏览器一样。因此使用 Selenium 的一些解决方法:

from selenium import webdriver
#Initiate your browser
browser = webdriver.Firefox() 
#It's Firefox in my case, you can have Chrome or Safari or Opera, depending upon the webdriver you have installed in your system
url = 'https://twitter.com/search?f=images&vertical=news&q=Iran'
#Fetch the URL in the 'browser'
browser.get(url)
#Get the page source of the browser
soup = BeautifulSoup(browser.page_source, 'html.parser')
#This page source is pretty similar to the one you see in your inspect element
browser.close() #'browser' has finished it's work, so 'close()' it
#Now apply whatever function you wish to on the webpage
spans = soup.findAll("span", {"class": lambda x: x and x.startswith('Adaptive')})
print(spans)

推荐阅读