Python BeautifulSoup 蜘蛛不工作

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 上没有任何错误,为什么它不起作用?

可能是因为,您打算从 0 而不是 1 初始化页面变量。目前,它从未进入循环。 因为,page 和 max page 都具有相同的值,即 1。

您将 1 作为 max_pages 参数传递给函数 spider。但是,您的 while 循环只会在 page < max_pages 时执行。 1 < 1 不正确。

您的代码中存在重大错误:

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 循环内。