【问题标题】:Why does my code scrape only scrape the first 3 pictures, not all of them?为什么我的代码只抓取前 3 张图片,而不是全部?
【发布时间】:2020-06-04 05:29:13
【问题描述】:

我正在尝试学习如何使用 beautifulsoup 进行网页抓取,并按照在线指南抓取了 subreddit 的一些婴儿尤达照片。这是我的代码:

from bs4 import BeautifulSoup
import requests
import urllib.request 

headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"}
url = "https://www.reddit.com/r/BabyYoda/"
response=requests.get(url,headers=headers)
soup = BeautifulSoup(response.content, 'lxml')

pics=soup.find_all("img",attrs = {"alt":"Post image"})

number=0
for image in pics:
    image_src=image["src"]
    print(image_src)
    #urllib.request.urlretrieve(image_src,str(number))
    number+=1

输出:

https://preview.redd.it/ps7dvuuccm251.jpg?width=640&crop=smart&auto=webp&s=5ba4ce4c000ea8694e594849a9f4b0c9ed14a7d1
https://preview.redd.it/wztcej6fvi251.jpg?width=640&crop=smart&auto=webp&s=879664f218e53b62de7a7d390a0bb70b6baa302c
https://preview.redd.it/0dqi2d6s7k251.jpg?width=640&crop=smart&auto=webp&s=5a98bb4431d9c07bfd0912faae6dfb0c15aba058

这只会给我前 3 张图片。我认为问题在于网页在您滚动时不断更新,从而产生更多图像。我不确定我以 HTML 格式下载的网页是否包含所有这些信息。谁能确认或看看为什么我没有得到所有的图像?

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    您可以通过保存网页来测试...如果只有 3 张图片就意味着您的理论是正确的,即页面在滚动时加载..

    【讨论】:

      【解决方案2】:

      Beautiful Soup 只会在页面加载时提取数据。您可以通过右键单击并选择查看页面源代码来查看。您提供的 URL 具有无限滚动(通过向下滚动加载附加数据)。要解决这个问题,您可以使用selenium

      【讨论】:

        猜你喜欢
        • 2021-05-21
        • 1970-01-01
        • 2018-02-12
        • 1970-01-01
        • 2019-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多