【问题标题】:pagination : why it's still run while the page is not match?分页:为什么页面不匹配时它仍在运行?
【发布时间】:2018-09-04 14:48:48
【问题描述】:

我想从网站上抓取数据,但首先我想获取带有分页的页面。这里我使用 python 作为程序语言,我已经得到了这个代码。但是当我运行它时,它不能正常工作。当 response.url 与 expected_url 不匹配时,必须停止结果。有人知道如何解决吗?请帮忙,谢谢。 这是代码:

from bs4 import BeautifulSoup
import urllib.request

count = 0
url = "http://www.belanjamimo.net/foundation-bb-cream/?o=a&s=%d"


def get_url(url):
    req = urllib.request.Request(url)
    return urllib.request.urlopen(req)

expected_url = url % count
response = get_url(expected_url)

while (response.url == expected_url):
    print("GET {0}".format(expected_url))
    count += 9
    expected_url = url % count
    response = get_url(expected_url)

【问题讨论】:

  • 它永远不会停止,因为你的条件在这个网站上永远是True,即使没有数据也可以调用belanjamimo.net/foundation-bb-cream/?o=a&s=63
  • 当它到达总页的末尾时如何停止它?
  • 在wihle循环结束时,您可以检查“下一页按钮”列表元素是否被禁用并添加中断语句

标签: python web-scraping pagination


【解决方案1】:

尝试以下方法来耗尽不同页面中的所有项目,并在没有更多可用项目时跳出循环。

from bs4 import BeautifulSoup
import requests

url = "http://www.belanjamimo.net/foundation-bb-cream/?o=a&s={}"

page = 0
while True:
    res = requests.get(url.format(page))
    soup = BeautifulSoup(res.text,"lxml")
    items = soup.select(".product-block h2 a")
    if len(items)<=1:break  #check out if there is any product still available
    for item in items:
        print(item.text)

    page+=9

【讨论】:

  • 我已经尝试过这段代码,并添加了一些代码来获取属性..所以,例如网络只有5页,但为什么它仍然打印6页? @SIM
  • 你肯定用错了脚本。您可以在这行 if len(items)&lt;=1:break 之后使用这行 print(res.url) 来确定它是否在给你正确的包含数据的 url 计数。顺便感谢您的快速回复。
  • 它适用于我在问题中提到的网络,但它不适用于不同的网络..是因为每个网络都有不同的设置吗?
猜你喜欢
  • 2021-03-30
  • 2016-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 2019-10-19
  • 2020-09-03
  • 2019-09-06
相关资源
最近更新 更多