【问题标题】:Trying to scrape image and I get empty output试图抓取图像,我得到空输出
【发布时间】:2021-01-11 21:37:03
【问题描述】:

我正在尝试抓取 Twitter 帐户图像,我尝试了多种方法,但输出一直给我空列表!

我的代码:

import requests
from bs4 import BeautifulSoup


url = requests.get('https://twitter.com/jack/photo')
soup = BeautifulSoup(url.text, 'lxml')
image = soup.find_all('img')

print(image)

输出:

[]

这是我项目的一部分.. 我尝试了 lxml 并按类查找,但我仍然一无所获,也许我在那里遗漏了一些东西,但我不知道它是什么。 如果有人可以帮助我,我将不胜感激。

提前致谢

【问题讨论】:

  • 推特正在使用某种前端框架。当您查看页面的源代码时,我检查了根本没有 img 标签。尝试使用硒
  • 是的,我可以使用 selenium,但我希望使用 BeautifulSoup 或 lxml 或 scrapy,但不是 selenium,因为我想将项目托管到 HeroKu,而 selenium 不适合 HeroKu .

标签: python python-3.x web-scraping beautifulsoup lxml


【解决方案1】:

我可以看到页面中使用了一些 React。如果您打开页面并检查元素,您会看到只要单击照片放大,就会出现一个新的 div,就像凭空出现的一样。这意味着它是由 react 创建的。

为了解决这个问题,您需要使用Seleniumvirtual browser 中打开页面,让JavaScript 发挥作用,然后查找img 标记。

【讨论】:

  • 是的,我尝试了 selenium,它工作正常,但我希望它与 BeautifulSoup 或 lxml 或任何其他抓取库一起使用,我不想使用 selenium,因为它不适用于 HeroKu (我想最终主持我的项目)
  • 不幸的是,除非您能找出网页从何处以及如何从其中提取图像(例如,如果它有某种形式的 API 可以用来获取图像),您将需要 JS为您呈现页面,这意味着使用 Selenium 之类的东西。
  • 可能有一些其他的方法可以解决它,正如其他响应所表达的那样。
【解决方案2】:

您正在尝试为 JavaScript twitter 搜索路径。如果您检查页面的响应,您将看到以下代码段。

    <form action="https://mobile.twitter.com/i/nojs_router?path=%2Fjack%2Fphoto" method="POST" style="background-color: #fff; position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 9999;">
  <div style="font-size: 18px; font-family: Helvetica,sans-serif; line-height: 24px; margin: 10%; width: 80%;">
    <p>We've detected that JavaScript is disabled in your browser. Would you like to proceed to legacy Twitter?</p>
    <p style="margin: 20px 0;">
      <button type="submit" style="background-color: #1da1f2; border-radius: 100px; border: none; box-shadow: none; color: #fff; cursor: pointer; font-size: 14px; font-weight: bold; line-height: 20px; padding: 6px 16px;">Yes</button>
    </p>
  </div>
</form>

我建议在您的浏览器中禁用 javascript,然后弄清楚如何查看这样的照片。然后你可以使用 requests 来模仿这些请求。

对我有用的是向路径发送请求: https://mobile.twitter.com/jack

然后使用 css 选择器:class= "avatar"。应该有一个孩子,一个图片标签,抓取该图片标签的 src,这应该是您照片的链接。

根据要求,这是我使用的python代码:

import requests
from bs4 import BeautifulSoup


response = requests.get('https://mobile.twitter.com/jack')

soup = BeautifulSoup(response.text, 'lxml')

avatars = soup.findAll("td", {"class": "avatar"})

print(avatars[0].findAll('img')[0].get('src'))

注意:Twitter 经常更改其布局,因此这可能无法长时间使用。

【讨论】:

  • 非常感谢,我更改了链接并写了image = soup.find_all('div', {"class: css-9pa8cd"}) print(image) 并且仍然是空列表,老实说,我不知道如何使用 css 选择器以及如何使用 BeautifulSoup 吸引,你能告诉我吗给我你的代码或解释我如何得到它?
猜你喜欢
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 2017-09-05
  • 1970-01-01
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多