【问题标题】:Not able to find a link in a product page无法在产品页面中找到链接
【发布时间】:2019-08-16 14:24:49
【问题描述】:

我正在尝试列出产品页面内的链接。

我有多个链接,我想通过这些链接获取产品页面的链接。

我只是发布单个链接的代码。

r = requests.get("https://funskoolindia.com/products.php?search=9723100")
soup = BeautifulSoup(r.content)
for a_tag in soup.find_all('a', class_='product-bg-panel', href=True):
    print('href: ', a_tag['href'])

这是它应该打印的内容:https://funskoolindia.com/product_inner_page.php?product_id=1113

【问题讨论】:

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

该站点是动态的,因此,您可以使用selenium

from bs4 import BeautifulSoup as soup
from selenium import webdriver
d = webdriver.Chrome('/path/to/chromedriver')
d.get('https://funskoolindia.com/products.php?search=9723100')
results = [*{i.a['href'] for i in soup(d.page_source, 'html.parser').find_all('div', {'class':'product-media light-bg'})}]

输出:

['product_inner_page.php?product_id=1113']

【讨论】:

  • 对于动态加载的页面,我几乎总是说它值得 Scrapy 代替
  • @AeroBlue 你可能是对的,但是,我不使用 Scrapy :) 你能用 Scrapy 发布解决方案吗?
  • 驱动程序的路径应该是什么。我在磁盘中没有看到任何 chrome 驱动程序......这给了我错误
【解决方案2】:

数据是通过 Javascript 从不同的 URL 动态加载的。一种解决方案是使用 selenium - 以这种方式执行 Javascript 并加载链接。

其他解决方案是使用re 模块并手动解析数据url:

import re
import requests
from bs4 import BeautifulSoup

url = 'https://funskoolindia.com/products.php?search=9723100'
data_url = 'https://funskoolindia.com/admin/load_data.php'

data = {'page':'1',
    'sort_val':'new',
    'product_view_val':'grid',
    'show_list':'12',
    'brand_id':'',
    'checkboxKey': re.findall(r'var checkboxKey = "(.*?)";', requests.get(url).text)[0]}

soup = BeautifulSoup(requests.post(data_url, data=data).text, 'lxml')

for a in soup.select('#list-view .product-bg-panel > a[href]'):
    print('https://funskoolindia.com/' + a['href'])

打印:

https://funskoolindia.com/product_inner_page.php?product_id=1113

【讨论】:

  • 这项工作正常,但现在我必须从提取的 url 中获取产品的详细信息,我认为这也是动态的,所以我该怎么办..这是re 方法吗?在提取的链接上还是我必须使用硒。?
  • @jamesjoyce 你可以做实验。 selenium 有它的开销,所以它比 requests + re 方法慢。我建议查看 Chrome/Firefox 开发人员工具并查看页面从何处加载数据 - 然后将该 URL 与 requests 一起使用。
【解决方案3】:

试试这个:print('href: ', a_tag.get("href")) 并将features="lxml" 添加到 BeautifulSoup 构造函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 2018-12-16
    相关资源
    最近更新 更多