【问题标题】:Bs4 find p tags by classbs4 按类别查找 p 个标签
【发布时间】:2019-10-11 13:45:48
【问题描述】:

我正在尝试制作此代码来抓取网站以获取产品名称。我正在尝试查找具有特定类的 p 标签。这是代码,当我运行它时它只是打印出来。我试图抓取的元素已被注释。

#<p class="product-name">Yaesu FT-DX101D HF/50MHz 100W SDR</p>


import requests
import urllib.request
import time
from bs4 import BeautifulSoup

url = "https://www.gigaparts.com/products/radios-amps-and-repeaters#/?Category1=Radios&Category2=Radios%2C+Amps+and+Repeaters&Category3=Radio+Transceivers&search_return=all&Category4=Base+Stations"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
for i in range(10):
    a_tags = soup.find("p", {"class": "product-name"})
    print(a_tags)
    time.sleep(2)

【问题讨论】:

  • 如果循环和time.sleep 的目的是“等待”直到所有元素都可见,那么它不会起作用。您只需要解析响应并构建soup 对象一次。它永远不会改变。如果该页面是使用 JS 动态加载的,那么 BeautifulSoup 不是正确的工具。您将需要使用seleniummechanize 或任何其他无头解决方案
  • 无论如何,尝试print(response.text) 并搜索元素。如果不存在,则该页面确实依赖于 JS,需要使用我之前评论中的其他工具

标签: python web-scraping beautifulsoup


【解决方案1】:

您可以模仿 jquery xhr,但删除所有多余且看起来最有可能随时间变化的内容。

import requests, re, json, ast
from bs4 import BeautifulSoup

r = requests.get('https://gigaparts-v2.ecomm-nav.com/nav.js?initial_url=https%3A%2F%2Fwww.gigaparts.com%2Fproducts%2Fradios-amps-and-repeaters%23%2F%3FCategory1%3DRadios%26Category2%3DRadios%252C%2BAmps%2Band%2BRepeaters%26Category3%3DRadio%2BTransceivers%26search_return%3Dall%26Category4%3DBase%2BStations&nxt_custom_options=formKey%3D%26groupId%3DNOT%2BLOGGED%2BIN&Category1=Radios&Category2=Radios%2C+Amps+and+Repeaters&Category3=Radio+Transceivers&search_return=all&Category4=Base+Stations&callback=jQuery0')
p = re.compile(r'jQuery0\((.*)\);')
d = ast.literal_eval(p.findall(r.text)[0])
soup = bs(d['content'], 'lxml')
product_names = [i.text for i in soup.select('.product-name')]
print(product_names )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 2021-03-18
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多