我正在尝试使用BeautifulSoup4来帮助我从Imgur下载一张图片,尽管我怀疑Imgur部分是否相关。举个例子,我在这里使用网页:https://imgur.com/t/lenovo/mLwnorj
我的代码如下:
import webbrowser, time, sys, requests, os, bs4 # Not all libraries are used in this code snippet
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("https://imgur.com/t/lenovo/mLwnorj")
res = requests.get(https://imgur.com/t/lenovo/mLwnorj)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, features="html.parser")
imageElement = soup.findAll('img', {'class': 'post-image-placeholder'})
print(imageElement)
Imgur链接上的HTML代码包含如下部分:
<img alt="" src="//i.imgur.com/JfLsH5y.jpg" class="post-image-placeholder" style="max-width: 100%; min-height: 546px;" original-title="">
我通过使用Inspect元素中的point-and-click工具选择页面上的第一个图像元素找到了它。你知道吗
问题是imageElement中应该有两个项,每个图像一个,但是print函数显示[]
。我也尝试过其他形式的soup.findAll('img', {'class': 'post-image-placeholder'})
,比如soup.findall("img[class='post-image-placeholder']")
,但没有什么不同。你知道吗
此外,当我使用
imageElement = soup.select("h1[class='post-title']")
,只是为了测试,print函数确实返回了一个匹配项,这让我怀疑它是否与标记有关。你知道吗
[<h1 class="post-title">Cable management increases performance. </h1>]
谢谢你的时间和努力
如果网站将在页面加载后插入对象,则需要使用Selenium而不是
requests
。你知道吗这里的基本问题似乎是当第一次加载页面时实际的
<img ...>
元素不存在。在我看来,最好的解决方案是利用SeleniumWebDriver,您已经可以使用它来获取图像。Selenium将允许页面正确呈现(使用JavaScript和all),然后定位您关心的任何元素。你知道吗例如:
我不能说我已经测试了这段代码,但是一般的概念应该有用。你知道吗更新:
我继续进行测试,修复了代码中的一些错误,然后得到了我希望看到的结果:
相关问题 更多 >
编程相关推荐