首页 > 解决方案 > 用 python 和漂亮的汤从网站上抓取代码

问题描述

我的项目是关于抓取 5 个购物网站。我从 StackOverflow 和 youtube 中找到了有用的数据。但我被困在一个网站上。一个 div 类使用样式显示,没有和隐藏的可见性,之后所有 div 类都被隐藏。我尝试使用 ajax、google chrome extension for javascript,并应用了我在其他 4 个中应用的不同方法,但这个网站对我来说有点难。如果有人帮助我阅读这些标签,以便我可以从网站上抓取数据,这将是有益的。网站网址是:网站

目前,我正在使用简单的代码进行解析。这是我使用的代码。

 y = requests.get(url)

 soup = BeautifulSoup(y.text, "html.parser")
 products = soup.find('div', class_='container min-w1170')
 products = products.find('div', class_='row mgt25')

 print(products)

 products = products.find_all("div", class_="findify-components-common--grid__column findify-components-common--grid__column-6")
 print(products)

直到第一次打印,所有 div 类都在工作,但在那之后,我无法从下一个 div 类中找到数据。

标签: pythonhtmlpython-3.xbeautifulsoup

解决方案


该脚本将为您提供所需的一切。使用 beautifulsoup 的诀窍是仔细分析 html 并寻找元素中的模式。您的代码中的错误可能是使用了错误的属性值。

from bs4 import BeautifulSoup
import requests
from selenium import webdriver
from socket import socket

url = 'https://homeshopping.pk/search.php?q=dell'
browser = webdriver.Firefox()
browser.get(url)
html = browser.page_source
soup = BeautifulSoup(html,features='html.parser')

products = soup.find_all('div',{'class':'findify-components--cards--product innerp product-box'})  # the div for each product tile
for product in products:
    name = (product.find('span',{'class':'findify-components--text findify-components--cards--product__title'})).get_text()
    price = (product.find('span',{'class':'price findify-components--cards--product--price__price'})).get_text()
    img_src = product.find('img')
    all_urls = product.find_all('a')
    product_url = all_urls[1]   # it will always be the second one
    product_url_only = product_url['href']

推荐阅读