我是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')
你能帮忙吗。在
在导入模块^{cd1>}时,请小心。在这种情况下,当您迭代时,第2行上的^{cd2>}将在^{cd3>}循环中被重写。
以下是一个较短的解决方案,它还将仅返回包含https的URL,作为href属性的一部分:
但是,这会绘制一个不完整的图片,因为并非所有链接都是因为页面上有HTML标记的错误而捕获的。我也可以推荐以下的替代方案,它非常简单,在您的场景中工作完美(note:您需要包Requests-HTML):
^{pr2}$这将输出所有URL,包括引用同一域上其他URL的URL和外部网站的URL。
我会考虑使用attribute=value css选择器并使用
^
运算符指定href
属性以https
开头。你将只有有效的协议。另外,使用set comprehension来确保没有重复,并使用Session
来重用连接。在相关问题 更多 >
编程相关推荐