当我尝试运行下面的代码时,返回了此错误。如果有人可以帮助指出我做错了什么,我将不胜感激。谢谢。
Traceback (most recent call last):
File "web_crawler.py", line 26, in <module>
links = get_all_links(page)
File "web_crawler.py", line 14, in get_all_links
url, endpos = get_next_target(page)
File "web_crawler.py", line 2, in get_next_target
start_link = page.find("<a href=")
TypeError: a bytes-like object is required, not 'str'
def get_next_target(page):
start_link = page.find("<a href=")
if start_link == -1:
return None, 0
start_quote = page.find('"',start_link)
end_quote = page.find('"',start_quote+1)
url = page[start_quote+1:end_quote]
print(url)
return url, end_quote
def get_all_links(page):
links = []
while True:
url, endpos = get_next_target(page)
if url:
links.append(url)
page = page[endpos:]
else:
break
return links
import requests
url='https://en.wikipedia.org/wiki/Moon'
r = requests.get(url)
page = r.content
links = get_all_links(page)
答案 0 :(得分:3)
response.content
是请求的原始内容。它们不会被解码或任何东西,它只是原始字节。
您想要使用的是response.text
属性,它将解码后的内容包含为字符串。
(您可能也想使用像BeautifulSoup这样的html解析库,而不是当前的page.find
方法