首页 > 解决方案 > 不能让我的脚本使用参数生成特定的 url

问题描述

我使用 python 创建了一个脚本来仅获取显示网页中有多少数据的内容。当我尝试在我的脚本中使用的链接时,我看到的结果类似于Showing 1-30 of 18893(这不是我想要的),但是Showing 1-30 of 196当我尝试下面的链接时我得到了(预期的输出)。底线是>我使用直接链接获得了成功,但是当脚本使用由 params 生成的 url 时,我得到了其他东西。

该网站的网址

我试过了:

import requests
from bs4 import BeautifulSoup

link = "https://www.yelp.com/search?"

params = {
    'find_desc': 'Restaurants',
    'find_loc': 'New York, NY',
    'l: p':'NY:New_York:Manhattan:Alphabet_City'
}

resp = requests.get(link,params=params)
soup = BeautifulSoup(resp.text,"lxml")
total = soup.select_one("p:contains(Showing)").text
print(total)

得到:

Showing 1-30 of 18894

预期输出:

Showing 1-30 of 196

此外,我使用的链接resp.url

https://www.yelp.com/search?find_desc=Restaurants&find_loc=New+York%2C+NY&l%3A+p=NY%3ANew_York%3AManhattan%3AAlphabet_City

但我期望的链接是:

https://www.yelp.com/search?find_desc=Restaurants&find_loc=New%20York%2C%20NY&l=p%3ANY%3ANew_York%3AManhattan%3AAlphabet_City

如何使脚本填充内容的正确 url?

标签: pythonpython-3.xweb-scraping

解决方案


你的参数有错别字'l: p':'NY:New_York:Manhattan:Alphabet_City'

urllib.parse.parse_qs使用然后复制参数是个好主意,而不是尝试自己解码。

这是固定版本:

import requests
from bs4 import BeautifulSoup

link = "https://www.yelp.com/search"

params = {
    'find_desc': 'Restaurants',
    'find_loc': 'New York, NY',
    'l': 'p:NY:New_York:Manhattan:Alphabet_City'
}

res = requests.get(link,params=params)
soup = BeautifulSoup(res.text, 'html.parser')
print(res.url)
total = soup.select_one("p:contains(Showing)").text
print(total)

输出:

https://www.yelp.com/search?find_desc=Restaurants&find_loc=New+York%2C+NY&l=p%3ANY%3ANew_York%3AManhattan%3AAlphabet_City
Showing 1-30 of 196

推荐阅读