【问题标题】:Scraping ecomm website for products info listed on one single page抓取 ecomm 网站以获取在一页上列出的产品信息
【发布时间】:2016-09-10 19:32:30
【问题描述】:

我试图抓取 Flipkart.com(我随机打开了一个显示 60 种产品的类别)。

但是,当我搜索所有链接时使用BeautifulSoup,我没有得到指向每个产品的链接。我获得了 37 个链接,其中没有一个指向产品描述页面....帮助!!!

import requests
from bs4 import BeautifulSoup

# a random product listing page 
url='https://www.flipkart.com/search?q=mobile&sid=tyy/4io&as=on&as-show=on&otracker=start&as-pos=1_1_ic_mobile'       

r=requests.get(url)

soup=BeautifulSoup(r.text,from_encoding="utf-8")
links=soup.find_all('a')

它给出了除了链接toproduct descrtiption页面之外的所有链接。

【问题讨论】:

  • data-reactid 在返回的第一个 url 中为您提供了一个很好的线索来了解原因

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


【解决方案1】:

据我了解(警告,我是菜鸟):当您使用普通浏览器打开有问题的页面时,页面中有 javascript,在处理时会创建额外的 html,您的浏览器会将这些 html 添加到它显示的文档中你。当您使用 requests 模块获取页面 html 时,它不会处理此 javascript,因此它永远不会获取此额外内容。您想要的信息包含在这个缺失的内容中。所以:

基于此线程的代码:Web-scraping JavaScript page with Python

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
from bs4 import BeautifulSoup


# Take this class for granted.Just use result of rendering.
class Render(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.mainFrame().load(QUrl(url))
        self.app.exec_()

    def _loadFinished(self, result):
        self.frame = self.mainFrame()
        self.app.quit()


url = 'https://www.flipkart.com/search?q=mobile&sid=tyy/4io&as=on&as-show=on&otracker=start&as-pos=1_1_ic_mobile'
r = Render(url)
result = r.frame.toHtml()
soup = BeautifulSoup(result, 'lxml')
links = soup.find_all('div', {'class': 'col col-7-12'})
target_links = [link.parent.parent.parent for link in links]
for link in target_links:
    try:
        print(link.find('a')['href'])
    except TypeError:  # we caught unwanted links in the find_all
        pass

我确信我引导链接的方式可以改进。

【讨论】:

    猜你喜欢
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多