【问题标题】:How to use Request with query parameter in Python?如何在 Python 中使用带有查询参数的请求?
【发布时间】:2021-07-14 05:55:18
【问题描述】:

我想从电子商务网站获取数据。但是,我可以得到产品但不超过 24 个。该站点正在使用页面索引查询参数。我正在发送查询参数,但脚本仍然获得 24 个产品。

代码、结果和网址 --> Screenshots

代码:

import requests
import sqlite3
from bs4 import BeautifulSoup

db = sqlite3.connect('veritabani.sqlite')
cursor = db.cursor()
cursor.execute("CREATE TABLE products (id, product, price)")
url = 'https://www.trendyol.com/cep-telefonu-x-c103498'
html_text = requests.get(url,params={'q': 'pi:5'}).text
soup = BeautifulSoup(html_text, 'lxml')
print(soup.contents)
products = soup.find_all("div", {"class": "p-card-wrppr"})
for product in products:
    product_id = product['data-id']
    product_name = product.find("div", {"class": "prdct-desc-cntnr-ttl-w two-line-text"}).find("span",{"class": "prdct-desc-cntnr-name"})["title"]
    price = product.find_all("div", {"class": "prc-box-sllng"})[0].text
    cursor.execute("INSERT INTO products VALUES (?,?,?)", (product_id,product_name,price))
    print(product_id,product_name,price)
db.commit()
db.close()

【问题讨论】:

  • 不清楚:您的意思是您希望页面尺寸更大,还是设置pi(页面索引?)您仍然可以获得前 25 个结果?

标签: python python-requests request


【解决方案1】:

您提到的网站使用滚动分页。但是你仍然可以获得你想要的数据。

首先,您传递的参数是错误的。尝试更改此行

html_text = requests.get(url,params={'q': 'pi:5'}).text

用这个:

html_text = requests.get(url,params={'pi':'5'}).text

您将在第 5 页获得 24 种产品。 所以基本上,你可以这样:

for i in range(10):
    html_text = requests.get(url,params={'pi': str(i)}).text
    soup = BeautifulSoup(html_text, 'lxml')
    print(soup.contents)
    products = soup.find_all("div", {"class": "p-card-wrppr"})
    for product in products:
        product_id = product['data-id']
        product_name = product.find("div", {"class": "prdct-desc-cntnr-ttl-w two-line-text"}).find("span",{"class": "prdct-desc-cntnr-name"})["title"]
        price = product.find_all("div", {"class": "prc-box-sllng"})[0].text
        cursor.execute("INSERT INTO products VALUES (?,?,?)", (product_id,product_name,price))
        print(product_id,product_name,price)
    db.commit()
    db.close()

这应该让你的产品在 10 页上。

【讨论】:

  • 谢谢。有用。我了解参数部分。但是为什么要使用 for 循环呢?
  • 如果你想在一次脚本执行中遍历网站的多个页面,那么你必须使用一些循环
  • 现在,我明白了。它就像一个页面。每 24 个产品不同的页面索引。所以我给 pi 分配了不同的数字,我总是得到 24 种产品。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 2018-10-15
  • 2023-02-10
  • 2021-09-22
  • 2016-06-04
  • 2013-05-30
  • 2018-06-29
相关资源
最近更新 更多