【问题标题】:Python: Simple Web Crawler using BeautifulSoup4Python:使用 BeautifulSoup4 的简单网络爬虫
【发布时间】:2016-10-31 11:42:06
【问题描述】:

我一直在关注 TheNewBoston 使用 Pycharm 的 Python 3.4 教程,目前正在学习如何创建网络爬虫的教程。我只想下载 XKCD 的所有漫画。使用看起来很容易的存档。这里是my code,后面是TheNewBoston。 每当我运行代码时,什么都没有发生。它运行并说,“进程以退出代码0完成”我在哪里搞砸了?
TheNewBoston 的教程有点过时,用于抓取的网站已更改域。我将评论视频中似乎很重要的部分。

我的代码:

mport requests
from urllib import request
from bs4 import BeautifulSoup

def download_img(image_url, page):
    name = str(page) + ".jpg"
    request.urlretrieve(image_url, name)


def xkcd_spirder(max_pages):
    page = 1
    while page <= max_pages:
        url = r'http://xkcd.com/' + str(page)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text, "html.parser")
        for link in soup.findAll('div', {'img': 'src'}):
            href = link.get('href')
            print(href)
            download_img(href, page)
        page += 1

xkcd_spirder(5)

【问题讨论】:

  • 你还没有解释发生了什么问题,或者问了一个问题......?不过,我猜你在download_img 中说name 'page' is undefined 时会出错——因为page 只存在于xkcd_spirder 中,你不能在其他地方使用它。您需要将其作为参数传递给download_img。
  • 我只是尝试了我假设你的意思。还是很新的。这是新代码。和以前一样的问题。还编辑了原始帖子以实际遇到我的问题。有点激动,哈哈。 pastebin.com/nv6X7S0M

标签: python web beautifulsoup


【解决方案1】:

comic在id为comic的div中,你只需要从img中拉出src > 在该 div 中,然后将其加入 base url,最后请求内容并写入,我使用 basename 作为名称来保存文件。

我还用范围循环替换了您的 while,并仅使用请求完成了所有 http 请求:

import requests
from bs4 import BeautifulSoup
from os import path
from urllib.parse import urljoin # python2 -> from urlparse import urljoin 


def download_img(image_url, base):
     # path.basename(image_url) 
    #  http://imgs.xkcd.com/comics/tree_cropped_(1).jpg -> tree_cropped_(1).jpg -
    with open(path.basename(image_url), "wb") as f:
        # image_url is a releative path, we have to join to the base 
        f.write(requests.get(urljoin(base,image_url)).content)


def xkcd_spirder(max_pages):
    base = "http://xkcd.com/"
    for page in range(1, max_pages + 1):
        url = base + str(page)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text, "html.parser")
        # we only want one image
        img = soup.select_one("#comic img") # or .find('div',id= 'comic').img
        download_img(img["src"], base)

xkcd_spirder(5)

运行代码后,您会看到我们获得了前五幅漫画。

【讨论】:

    猜你喜欢
    • 2017-01-26
    • 2016-06-23
    • 2023-03-13
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多