我是 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/