【问题标题】:how to scrape data from telemart using python?如何使用 python 从 Telemart 中抓取数据?
【发布时间】:2020-04-16 07:29:14
【问题描述】:
import bs4
import requests
url = requests.get(
    'https://www.telemart.pk/mobile-and-tablets/mobile-phone.html')
soup = bs4.BeautifulSoup(url.text, features='lxml')
print(soup)

我想抓取价格、图片链接、产品链接、每件商品的标题,但数据在 XHR 中。那么我如何从 xhr 中抓取数据

【问题讨论】:

  • 您提供的链接下没有任何内容,只有:在此条件中未找到产品
  • 再看看我修改了它
  • 哦,它是网站动态下载的……你用requests是不会得到的。尝试使用Selenium,在加载一些动态内容后,您可以使用它来获取网站。检查例如这里:towardsdatascience.com/…
  • 但如果您在检查中看到,然后转到网络选项卡,然后转到 xhr,那么您可以看到“0”以及其中存在的所有数据

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

您可以使用 post http 请求从该页面获取内容,如下所示。

import requests
from bs4 import BeautifulSoup

link = 'https://www.telemart.pk/index.php/home/listed/click/{}'

payload = {
    'category': '35',
    'rating': '',
    'sub_category': '',
    'brand': '',
    'attributesids': '',
    'ishiddenprice': '0',
    'featured': '',
    'range': '6499;471999',
    'express_delivery': '',
    'text': '',
    'view_type': 'grid'
}

with requests.Session() as s:
    r = s.get(link)
    csrf_id = r.cookies['csrf_cookie_name']
    payload['csrf_test_name'] = csrf_id

    for i in range(0,144,48):
        res = s.post(link.format(i),data=payload,headers={"x-requested-with":"XMLHttpRequest"})
        soup = BeautifulSoup(res.text,"html.parser")
        for item in soup.select(".product-details"):
            product_name = item.select_one("h2.product-name").get_text(strip=True)
            price = item.select_one(".price > ins").get_text(strip=True)
            print(product_name,price)

【讨论】:

  • 如果我想从所有 3 个页面中获取列表怎么办?
  • 上述脚本已经在解析所有三个页面的内容。你实际上并没有通过答案,对吧?
  • 但是如果有5页那么让?
  • 这是5*48+1 创建最高范围的逻辑。还有其他方法,例如您可以解析最高分页数并乘以 48。但是,不要一次问多维问题。你一开始问的问​​题已经回答了。如果您还有其他问题,请确保创建一个新帖子。谢谢。
猜你喜欢
  • 2022-01-10
  • 1970-01-01
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多