簡體   English   中英

美麗的湯在一個網站上返回空列表,但在另一個網站上工作

[英]Beautiful soup returns empty list on one website, but works on another website

我目前正在通過“使用Python自動化無聊的東西”來學習Python。 我目前正在做Web Scraping部分。

我編寫了從一個網站獲取產品價格的代碼。 但是,當我稍微修改一下代碼以在另一個網站上無法正常工作時,Beautiful Soup從CSS返回一個空列表。

這是我的工作代碼。

import bs4, requests, re

def getPrice(productUrl):
    res = requests.get(productUrl)
    res.raise_for_status()

    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    # Go through CSS and get price
    source = soup.select('#product_addtocart_form > div.product-shop > div.details-info')
    element = source[0].text.strip()
    # Regex for getting the price from the rest of the CSS.
    pattern = re.compile(r"""R([1-9]\d*)(\.\d\d)?(?![\d.])""")

    # Get price from string using regex pattern
    trueprice = re.split(pattern, element)
    return("The product's price is : R " + trueprice[1])

product = "https://www.faithful-to-nature.co.za/green-home-paper-straws-in-compostable-bag"

weblink = getPrice(product)

print(weblink)

這是我編輯的另一個網站無效的代碼。 我注釋掉了一些代碼,因為它在列表中沒有數據時不起作用。

import bs4, requests, re

def getPrice(productUrl):
    res = requests.get(productUrl)
    res.raise_for_status() # Check for any errors in request

    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    # Go through CSS and get price
    csssource = soup.select('#shopfront-app > div > div.grid-container.pdp-grid-container > div.grid-x.grid-margin-x > div > div > div > div > div.cell.medium-auto > div.pdp-core-module_actions_mdYzm > div.sf-buybox.pdp-core-module_buybox_q5wLs.buybox-module_buybox_eWK2S')
    #element = csssource[0].text.strip()

    # Regex for getting the price from the rest of the CSS.
    pattern = re.compile(r"""R([1-9]\d*)(\.\d\d)?(?![\d.])""")

    #trueprice = re.split(pattern, element)
    #return("The product's price is : R " + trueprice[1])

    print(csssource)

test1 = "https://www.takealot.com/lego-classic-basic-brick-set-11002/PLID53430493"


weblink = getPrice(test1)

print(weblink)

在這兩個網站上,我都使用Chrome上的inspect方法獲得了CSS選擇器。 我嘗試使用更寬的CSS選擇器,但Beautiful Soup仍然返回一個空列表。

如何獲得Beautiful Soup返回正確的列表/ CSS選擇器?

嗨,我相信這個網站提供的是動態內容,所以您需要使用硒,當我嘗試僅用請求/ bs抓取時,我也會得到空白列表。 您可能可以使用原始的CSS選擇標准,但是我選擇了第5次出現的貨幣作為您嘗試獲得的價​​格。

下載正確的gecko驅動程序並在腳本中設置路徑。

https://github.com/mozilla/geckodriver/releases

from bs4 import BeautifulSoup
from selenium import webdriver
import time

#self.driver = webdriver.Firefox(executable_path = 'D:\Selenium_RiponAlWasim\geckodriver-v0.18.0-win64\geckodriver.exe')

driver = webdriver.Firefox()
driver.get('https://www.takealot.com/lego-classic-basic-brick-set-11002/PLID53430493')
html = driver.page_source
soup = BeautifulSoup(html,'lxml')
i = 0
for span in soup.find_all('span',{'class' : 'currency'}):
    if(i == 4):
        print(span.text)
    i += 1
#driver.close()
#returns R 315

如果查看瀏覽器中發生的請求,您會注意到該站點通過從https://api.takealot.com/rest/v-1-8-0的調用通過JSON獲取其產品詳細信息。 / product-details / {PRODUCT_ID}?platform = desktop(例如https://api.takealot.com/rest/v-1-8-0/product-details/PLID53430493?platform=desktop )。

因此,此站點而不是硒的另一個選擇是自己調用API。

import requests

def getProductInfo(productId):
    productUrl = 'https://api.takealot.com/rest/v-1-8-0/product-details/{0}?platform=desktop'.format(productId)
    res = requests.get(productUrl, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'})
    res.raise_for_status() # Check for any errors in request
    return res.json()

product = getProductInfo("PLID53430493")
print(product['buybox']['pretty_price'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM