繁体   English   中英

'BeautifulType'对象在Beautiful Soup 4中无法调用

[英]'NoneType' object is not callable in Beautiful Soup 4

我是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'对象不是可调用的第20行,在soup = bs.BeautifulSoup(url.urlopen(link).read(),'html.parser')

你能帮忙吗?

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

这是一个更简短的解决方案,该方案还将只返回包含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标记的错误,并非所有链接都被捕获,因此绘制的图片不完整。 我还可以推荐以下替代方案,它非常简单,并且在您的方案中完美运行( 注意 :您将需要包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。

我会考虑使用attribute = value css选择器并使用^运算符指定href属性以https开头。 这样您将只有有效的协议。 另外,使用set comprehensions确保没有重复,并确保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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM