[英]Python BeautifulSoup Spider is not working
嗨,我正在尝试学习如何使用python剪贴元素,并且试图获取网页标题(local.ch),但是我的代码无法正常工作,我也不知道为什么。
这是python代码:
import requests
from bs4 import BeautifulSoup
def spider(max_pages):
page = 2
while page < max_pages:
url = 'http://yellow.local.ch/fr/q/Morges/Bar.html?page=' + str(page)
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for link in soup.findAll('a', {'class':'details-entry-title-link'}):
title = link.string
print(title)
page += 1
spider(3)
我很确定代码是正确的,我在pycharm上没有任何错误,为什么它不起作用?
您的代码中有一个主要错误:
page = 1
while page < max_pages
....
spider(1)
永远不会满足该条件,并且其余代码也不会执行! 其他一些错误是编码错误和未指定的解析器警告:
import requests
from bs4 import BeautifulSoup
def spider(max_pages):
page = 1
while page <= max_pages:
url = 'http://yellow.local.ch/fr/q/Morges/Bar.html?page=' + str(page)
source_code = requests.get(url)
plain_text = source_code.text.encode("utf-8")
soup = BeautifulSoup(plain_text, 'html.parser')
for link in soup.findAll('a', {'class':'details-entry-title-link'}):
title = link.string
print(title.encode("utf-8"))
page += 1
spider(1)
注意编码"utf-8"
部分-如b
前缀所示,此编码将导致二进制输出。 如果没有此步骤, print()
函数将引发错误。 在plain_textplain_text = source_code.text.encode("utf-8")
行上进行了相同的更改。
另一个错误是page += 1
行的缩进错误。 它应该在while循环内。
可能是因为您打算将页面变量从0而不是1初始化。目前,它从未进入循环。 因为,页面和最大页面的值确实是1。
您将1作为max_pages
参数传递给功能spider
。 但是,仅在page < max_pages
执行while循环。 1 <1是不正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.