如何解决尝试刮擦图像,我得到空输出
我正在尝试抓取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并按类查找,但是我仍然一无所获,也许我在那里缺少一些东西,但是我不知道它是什么。 如果有人可以帮助我,我将非常感激。
预先感谢
解决方法
我可以在页面中看到一些React。如果打开页面并检查元素,您将看到,单击图片放大后,将立即出现一个新的div,就像从空中一样。这意味着该内容是由react创建的。
为了解决这个问题,您将需要使用Selenium在virtual browser
中打开页面,让JavaScript发挥作用,然后寻找img
标签。
您正在尝试抓取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,然后弄清楚如何查看此类照片。然后,您可以使用请求来模仿那些请求。
对我有用的是向该路径发送请求: 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经常更改其布局,因此可能不会长期有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。