python - 如何抓取嵌套的 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)
打印“跨度”时收到一个空列表
[]
解决方案
您想要的内容很可能被 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)
推荐阅读
- r - R / nse / 变量到子函数的双重切换
- azure-devops - 在 Azure DevOps 中,有没有一种方法可以快速查看工作项在积压工作中的位置?
- c# - 如何报告 WPF RichTextBox 无法正确呈现双倍行距的问题
- excel - Excel VBA 分别复制表格中的每一行
- c# - revit API (visual studio c#) 是否有一个函数可以为我提供有关用户单击了哪个按钮的信息?
- python - 在 python 中使用 selenium 模拟在网页区域外移动鼠标
- vba - 将 MS ACCESS 表数据附加到 Excel 表?
- c# - 切片实体框架的事务以减少内存使用
- django - django/apache 无法在 Docker 容器中提供网页。错误 - ModuleNotFoundError:没有名为“django”的模块
- python - Python Google Drive API - 获取 My Drive 文件夹的 ID