python - 不能让我的脚本使用参数生成特定的 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?
解决方案
你的参数有错别字'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
推荐阅读
- sql-server-2008 - 如何在点网核心中从前端处理长时间运行的程序(运行长达 2-4 小时)
- r - 从 R 中的两个不同数据帧创建一个数组
- python - Python升级导致终端...未打开
- python - 使用颜色条和滑块后如何修复绘图的标题位置
- shopify - 有什么方法可以通过 Shopify REST 或 GraphQL API 检索聚合?
- visual-studio - 启动失败,因为容器中的目录“/remote_debugger”为空
- xcode - 找不到“FLTFirebasePlugin”颤振的协议声明
- postgresql - 位置参数元组的替换索引 1 超出范围为什么会出现此错误?
- ruby-on-rails - 修改字符串的更简单方法
- swift - Swift:保持对弱变量的强引用