“NoneType”对象在Beautiful Soup 4中不可调用

2024-09-27 21:33:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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')

你能帮忙吗。在


Tags: inhttpscleanurlforgetbslink
2条回答

在导入模块^{cd1>}时,请小心。在这种情况下,当您迭代时,第2行上的^{cd2>}将在^{cd3>}循环中被重写。

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

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标记的错误而捕获的。我也可以推荐以下的替代方案,它非常简单,在您的场景中工作完美(note:您需要包Requests-HTML):

^{pr2}$

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

我会考虑使用attribute=value css选择器并使用^运算符指定href属性以https开头。你将只有有效的协议。另外,使用set comprehension来确保没有重复,并使用Session来重用连接。在

from bs4 import BeautifulSoup as bs
import requests
import pandas as pd
final = []

with requests.Session() as s:
    r = s.get('https://pythonprogramming.net/parsememcparseface/')
    soup = bs(r.content, 'lxml')
    httpsLinks = {item['href'] for item in soup.select('[href^=https]')}
    for link in httpsLinks:
        r = s.get(link)
        soup = bs(r.content, 'lxml')
        newHttpsLinks = [item['href'] for item in soup.select('[href^=https]')]
        final.append(newHttpsLinks)
tidyList =  list({item for sublist in final for item in sublist})  
df = pd.DataFrame(tidyList)
print(df)

相关问题 更多 >

    热门问题