【问题标题】:How to webscrape nested div and ol classes如何网页抓取嵌套的 div 和 ol 类
【发布时间】:2019-11-05 06:29:38
【问题描述】:

我正在尝试抓取this webpage

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

查找所有以“自适应”开头的跨度类 作为示例类将是“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)

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

[]

【问题讨论】:

  • 您是否检查了页面源中是否存在您要查找的元素?
  • 我正在寻找包含单词“Adaptive”的跨度类 - 这是在检查页面时发现的
  • 我推荐使用soup.select('span[class^=Adaptive]'),使用css选择器更酷
  • 你知道禁止网络抓取的 Twitter 服务条款,我希望? (“使用服务”twitter.com/en/tos 下的第 4 节) - 这可能会导致您的 IP 地址被禁止。为什么不使用 API?

标签: python html web-scraping twitter beautifulsoup


【解决方案1】:

您想要的内容很可能被 JS 脚本的力量所隐藏。我们的 request 库不会打扰那些 JS 脚本,它会获取在浏览器的 JSless 模式下对您可见的内容。 这个问题可以在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)

【讨论】:

    猜你喜欢
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多