python - 'NoneType' 对象在 Beautiful Soup 4 中不可调用

标签 python html python-3.x web-scraping beautifulsoup

我是 python 新手,开始尝试 Beautiful Soup 4。我尝试编写代码来获取一页上的所有链接,然后使用这些链接重复这些过程,直到解析整个网站。

import bs4 as bs
import urllib.request as url

links_unclean = []
links_clean = []
soup = bs.BeautifulSoup(url.urlopen('https://pythonprogramming.net/parsememcparseface/').read(), 'html.parser')

for url in soup.find_all('a'):
    print(url.get('href'))
    links_unclean.append(url.get('href'))

for link in links_unclean:
    if (link[:8] == 'https://'):
        links_clean.append(link)

print(links_clean)

while True:
    for link in links_clean:
        soup = bs.BeautifulSoup(url.urlopen(link).read(), 'html.parser')

        for url in soup.find_all('a'):
            print(url.get('href'))
            links_unclean.append(url.get('href'))

        for link in links_unclean:
            if (link[:8] == 'https://'):
                links_clean.append(link)

        links_clean = list(dict.fromkeys(links_clean))



input()

但我现在收到此错误:

'NoneType' object is not callable line 20, in soup = bs.BeautifulSoup(url.urlopen(link).read(), 'html.parser')

请帮忙。

最佳答案

将模块作为导入时要小心。在这种情况下,当您进行迭代时,第 2 行的 url 会在 for 循环中被覆盖。

这是一个较短的解决方案,它也将仅返回包含 https 作为 href 属性一部分的 URL:

from bs4 import BeautifulSoup
from urllib.request import urlopen


content = urlopen('https://pythonprogramming.net/parsememcparseface/')
soup = BeautifulSoup(content, "html.parser")
base = soup.find('body')

for link in BeautifulSoup(str(base), "html.parser").findAll("a"):
    if 'href' in link.attrs:
        if 'https' in link['href']:
            print(link['href'])

但是,这描绘了一幅不完整的图片,因为由于 HTML 标记页面上的错误,并未捕获所有链接。我还可以推荐以下替代方案,它非常简单并且在您的场景中完美运行(注意:您将需要包 Requests-HTML ):

from requests_html import HTML, HTMLSession

session = HTMLSession()
r = session.get('https://pythonprogramming.net/parsememcparseface/')

for link in r.html.absolute_links:
    print(link)

这将输出所有 URL,包括引用同一域中其他 URL 的 URL 和外部网站的 URL。

关于python - 'NoneType' 对象在 Beautiful Soup 4 中不可调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192919/

相关文章:

python - 转换 Pandas DataFrame,添加行值作为列标题

python - 用 python 绘制 3D 散点图?

html - 删除 CSS 按钮轮廓

将匹配图像移动到单独文件夹的 Python 脚本

python - 在 Python 中以列表、集合、字典的形式提取列

python - 在 PL/Python 函数之间重用纯 Python 函数

html - 如何使用打印按钮从html页面仅打印一个div内容

html - 为什么我的媒体查询没有响应?

python - 如何在 Python3.x 中检索单个 7zip 文件而不解压所有文件?

python - 在 Python 中使用 os.stat() 结果时如何忽略隐藏文件?