【问题标题】:find vs select_one give me different results in python web scrapingfind vs select_one 在 python 网络抓取中给了我不同的结果
【发布时间】:2020-02-16 00:08:23
【问题描述】:

嗨,我是 Python Beautiful Soup 的初学者。 我正在尝试从https://www.flipkart.com/laptops/~buyback-guarantee-on-laptops-/pr?sid=6bo%2Cb5g&uniqBStoreParam1=val1&wid=11.productCard.PMU_V2 抓取一个网站

当我使用 find 方法时,我可以得到产品的价格信息。 但是,使用 select_one 方法时,我无法获得任何有关价格的信息。

find
    import requests
    from bs4 import BeautifulSoup
    import pandas as pd
    r=requests.get('https://www.flipkart.com/laptops/~buyback-guarantee-on-laptops-/pr?sid=6bo%2Cb5g&uniqBStoreParam1=val1&wid=11.productCard.PMU_V2')
    soup=BeautifulSoup(r.text,'lxml')
    results=soup.find_all('a', attrs={'class':'_31qSD5'})
    for result in results:
        price=result.find('div',{'class':'_1vC4OE _2rQ-NK'}).text[1:]

选择一个

import requests
from bs4 import BeautifulSoup
import pandas as pd
r=requests.get('https://www.flipkart.com/laptops/~buyback-guarantee-on-laptops-/pr?sid=6bo%2Cb5g&uniqBStoreParam1=val1&wid=11.productCard.PMU_V2')
soup=BeautifulSoup(r.text,'lxml')
results=soup.select('._31qSD5')
result=results[0]
price=result.select_one('._1vC4OE _2rQ-NK').text[1:]

谁能启发我在 select_one 方法中获取价格信息?

【问题讨论】:

    标签: python web-scraping beautifulsoup css-selectors


    【解决方案1】:

    试试下面的方法怎么样? _2rQ-NK 类的这部分 -NK 似乎是独一无二的,因此您可以利用它来获取价格。

    import requests
    from bs4 import BeautifulSoup
    
    r = requests.get('https://www.flipkart.com/laptops/~buyback-guarantee-on-laptops-/pr?sid=6bo%2Cb5g&uniqBStoreParam1=val1&wid=11.productCard.PMU_V2')
    soup = BeautifulSoup(r.text,'lxml')
    for items in soup.select('._31qSD5'):
        price = items.select_one('[class$="-NK"]').text[1:]
        print(price)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      相关资源
      最近更新 更多