Python美女汤汽车排行榜刮刮乐

问题描述 投票:1回答:1

我需要从一些网站上搜罗汽车排名。

比如说

https:/www.kbb.comarticlesbest-cars10-best-used-cars-under-10000

  1. 2011款丰田凯美瑞
  2. 2013款本田思域...

https:/www.autoguide.comauto-news201910top-10-best-cars-for-snow.html

道奇Charger AWD斯巴鲁Outback日产Altima AWD... ...

我在检测网站上的排名时遇到了麻烦,因为它们都有点不同。我的目标基本上是有一个脚本,可以自动检测排名,并检索我所需要的数据(排名中的品牌+车型),在任何给定的汽车网站上,具有相当高的准确性。

我要收集的数据(排名中的品牌+车型)有时在H2、H3或H4中,有时在链接... 有时写成 "1.Brand1 Model1,2.Brand2 Model2..."。Brand2 Model2... "有时是 "Brand1 Model1,Brand2 Model2... "这要看....

我在Python中用BeautifulSoup做这个。

有什么好办法?

编辑:我在用Python和BeautifulSoup做这件事。

要说明的是,我在努力分析数据,而不是废掉它(见下面的评论).但为了让大家明白,下面是我处理上面第1个例子的方法。

for url in urls:
    req = requests.get(url)
    soup = BeautifulSoup(req.text, "lxml")


    for sub_heading in soup.find_all('h2'): 
        if  str(1) + ". " in sub_heading.text and "11." not in sub_heading.text: #filter applied to keep only strings starting with "1. "
             list_url.append(url)
             print(list_sub_heading)

RESULT:['1. 2011丰田凯美瑞']

python web-scraping beautifulsoup
1个回答
1
投票
import requests
from bs4 import BeautifulSoup


def main(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser')
    goal = [item.find_previous("h3").text for item in soup.findAll(
        "img", class_="alignnone")]
    mylist = list(dict.fromkeys(goal))
    print(mylist)


main("https://www.kbb.com/articles/best-cars/10-best-used-cars-under-10000/")

输出。

['1. 2011 Toyota Camry', '2. 2013 Honda Civic', '3. 2009 Toyota Avalon', '4. 2011 Honda Accord', '5. 2010 Toyota Prius', '6. 2012 Mazda Mazda3', '7. 2011 Toyota Corolla', '8. 2010 Subaru Outback', '9. 2013 Kia Soul', '10. 2012 Subaru Legacy']

re 版本。

import requests
import re


def main(url):
    r = requests.get(url)
    match = [f'{item.group(1)} {item.group(2)}'
             for item in re.finditer(r'>(\d+\.).+?>(.+?)<', r.text)]
    print(match)


main("https://www.kbb.com/articles/best-cars/10-best-used-cars-under-10000/")

输出:版本:输出。

['1. 2011 Toyota Camry', '2. 2013 Honda Civic', '3. 2009 Toyota Avalon', '4. 2011 Honda Accord', '5. 2010 Toyota Prius', '6. 2012 Mazda Mazda3', '7. 2011 Toyota Corolla', '8. 2010 Subaru Outback', '9. 2013 Kia Soul', '10. 2012 Subaru Legacy']
© www.soinside.com 2019 - 2024. All rights reserved.