【问题标题】:Error:None while trying to scrape data using BeautifulSoup错误:尝试使用 BeautifulSoup 抓取数据时无
【发布时间】:2020-08-06 10:23:10
【问题描述】:

我是网络抓取的新手。我正在尝试使用 BeautifulSoup 抓取标题(QCY T5 无线蓝牙耳机 V5.0 Touch Control Stereo HD 与 380mAh 电池通话),但它在输出中显示 None。 这是我尝试过的代码:

from bs4 import BeautifulSoup
import requests

page=requests.get('https://www.daraz.pk/products/qcy-t5-wireless-bluetooth-earphones-v50-touch-control-stereo-hd-talking-with-380mah-battery-i143388262-s1304364361.html?spm=a2a0e.searchlist.list.1.5b7c4a71Jr4QZb&search=1')
soup=BeautifulSoup(page.content,'html.parser')
print (page.status_code)

heading=soup.find(class_='pdp-mod-product-badge-title')
print(heading)

来自网站的html代码:

<div class="pdp-mod-product-badge-wrapper"><span class="pdp-mod-product-badge-title" data-spm-anchor-id="a2a0e.pdp.0.i0.4f257123ixGMNY">QCY T5 Wireless Bluetooth Earphones V5.0 Touch Control Stereo HD talking with 380mAh battery</span></div>

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    page.content 中没有“pdp-mod-product-badge-title”,正确的类是“breadcrumb_item_anchor_last”,您可以在浏览器的查看源代码中提取它。

    代码:

    from bs4 import BeautifulSoup
    import requests
    
    page=requests.get('https://www.daraz.pk/products/qcy-t5-wireless-bluetooth-earphones-v50-touch-control-stereo-hd-talking-with-380mah-battery-i143388262-s1304364361.html?spm=a2a0e.searchlist.list.1.5b7c4a71Jr4QZb&search=1')
    soup=BeautifulSoup(page.content,'html.parser')
    print (page.status_code)
    
    heading=soup.find(class_='breadcrumb_item_anchor_last')
    
    print(heading.text.strip()) #Thanks to @bigbounty
    

    【讨论】:

    • 使用print(heading.text.strip())
    【解决方案2】:

    您无法获取数据的原因是该网站的View Source没有您提到的类。

    初学者犯的一个基本错误是在页面的“检查”选项卡中查找元素并确定要抓取的类。永远不要这样做。

    为了所有数据的可靠性,请始终通过按 Ctrl + U 转到页面的查看源代码并查找您的内容。在大多数情况下,内容是通过使用 JS 文件和 API 调用动态呈现的,可以从网络选项卡中找到。

    对于上述问题,您要查找的信息也是动态加载的,并且在页面的源代码中不可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2018-07-31
      • 1970-01-01
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多