无法使我的脚本仅从顽固的网站中获取下一页的链接

MIT*_*THU 5 python web-scraping python-3.x

我已经在python中创建了一个脚本,以仅从遍历多个页面的网站中删除指向不同餐厅的链接。通过查看位于右上角的特定文本,我可以看到有多少链接:

显示1-30 of 18891

但是我无法手动或使用脚本来跳过此链接。该站点在每个分页中将其内容增加30。

到目前为止,我已经尝试过:

import requests
from bs4 import BeautifulSoup

link = 'https://www.yelp.com/search?find_desc=Restaurants&find_loc=New%20York%2C%20NY&start={}'

for page in range(960,1920,30): # modified the range to reproduce the issue

    resp = requests.get(link.format(page),headers={"User-Agent":"Mozilla/5.0"})

    print(resp.status_code,resp.url)

    soup = BeautifulSoup(resp.text, "lxml")
    for items in soup.select("li[class^='lemon--li__']"):

        if not items.select_one("h3 > a[href^='/biz/']"):continue
        lead_link = items.select_one("h3 > a[href^='/biz/']").get("href")
        print(lead_link)
Run Code Online (Sandbox Code Playgroud)

上面的脚本仅从其目标页面获取链接。

我如何也可以从其他页面获得链接?

小智 0

该页之后没有数据。

您的代码应修改为以下内容 -

import requests
from bs4 import BeautifulSoup

link = "https://www.yelp.com/search?find_desc=Restaurants&find_loc=New%20York%2C%20NY&start={}"

for page in range(0, 960, 30):  # modified the range to reproduce the issue

    resp = requests.get(link.format(page), headers={"User-Agent": "Mozilla/5.0"})

    print(resp.status_code, resp.url)

    soup = BeautifulSoup(resp.text, "lxml")
    for items in soup.select("li[class^='lemon--li__']"):

        if not items.select_one("h3 > a[href^='/biz/']"):
            continue
        lead_link = items.select_one("h3 > a[href^='/biz/']").get("href")
        print(lead_link)
Run Code Online (Sandbox Code Playgroud)