【问题标题】:AttributeError: 'NoneType' object has no attribute 'group' with BeautifulSoup4AttributeError:“NoneType”对象没有带有 BeautifulSoup4 的属性“组”
【发布时间】:2019-09-25 07:51:19
【问题描述】:

你好社区我有一个问题,我不知道如何解决我的问题是我编写了一个脚本来抓取带有 BeautifuleSoup4 的图像的网页,但我收到了错误(AttributeError:'NoneType' 对象没有属性'group')

import re
import requests
from bs4 import BeautifulSoup

site = 'https://www.fotocommunity.de/natur/wolken/3144?sort=new'

response = requests.get(site)

soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img', {"src": True})

urls = [img["src"] for img in img_tags]

for url in urls:
    filename = re.search(r'([\w_-]+[.](jpg|png))$', url)
    with open(filename.group(1), 'wb') as f:

        if 'http' not in url:
            # sometimes an image source can be relative
            # if it is provide the base url which also happens
            # to be the site variable atm.
            url = '{}{}'.format(site, url)
        response = requests.get(url)
        f.write(response.content)

【问题讨论】:

  • 这意味着您对filename 的正则表达式搜索没有返回任何结果。首先使用if 测试其真实性。
  • 但是我的问题是我没有得到任何照片并且没有错误:/
  • 因为你的正则表达式是错误的。我猜你只想要文件名?
  • 是的,我只想拥有文件名。抱歉,这是我的第一个爬虫 :)
  • 酷。在下面检查我的答案。

标签: python beautifulsoup


【解决方案1】:

你的正则表达式是错误的。如果您不熟悉正则表达式,请使用 Python 内部的 urllib 进行重量级提升,而不是编写正则表达式。

使用这样的东西(未经测试):

import re
import requests
from bs4 import BeautifulSoup
from urllib.parse import urlsplit  # import this additional library
from os.path import basename  # import this additional library

site = 'https://www.fotocommunity.de/natur/wolken/3144?sort=new'

response = requests.get(site)

soup = BeautifulSoup(response.text, 'html.parser')
images_div = soup.find(id=re.compile(r"fcx-gallery-\w+"))  # focus on the div containing the images
if img_tags:  # test if img_tags has any data
    img_tags = images_div.find_all('img', {"data-src": True})  # get all the images in that div

    urls = [img["data-src"] for img in img_tags]  # grab sources from data-source

    for url in urls:
        filename = basename(urlsplit(url).path)  # use this instead of a regex
        with open(filename, 'wb') as f:  # filename is now a string

            if 'http' not in url:
                # sometimes an image source can be relative
                # if it is provide the base url which also happens
                # to be the site variable atm.
                url = '{}{}'.format(site, url)
            response = requests.get(url)
            f.write(response.content)

【讨论】:

  • 很酷,它可以工作,但我没有得到每张照片只有 10,但我需要一点“更多”:D
  • 你检查过你有多少urls吗?我测试了你的代码到第 13 行,有 6 个 url。
  • 你在哪里找到这么多url我只能找到urls标签和抓取的url
  • 现在我得到这个错误 (KeyError: 'src') 我知道我必须先允许它,但是在哪里?
  • 我的错。我不小心删除了{"src": True}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-06
  • 1970-01-01
  • 2022-07-20
  • 2019-01-01
相关资源
最近更新 更多