【问题标题】:Data scraping from Vivino.com从 Vivino.com 抓取数据
【发布时间】:2020-09-24 16:59:12
【问题描述】:

我正在尝试从 vivino.com 收集数据,但 DataFrame 显示为空,我可以看到我的汤正在收集网站信息,但看不到我的错误在哪里。

我的代码:

def get_data():  

    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0", "Accept-Encoding":"gzip, deflate", "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "DNT":"1","Connection":"close", "Upgrade-Insecure-Requests":"1"}

    r = requests.get("https://www.vivino.com/explore?e=eJzLLbI1VMvNzLM1UMtNrLA1NTBQS660DQhRS7Z1DQ1SKwDKpqfZliUWZaaWJOao5SfZFhRlJqeq5dsmFierlZdExwJVJFcWA-mCEgC1YxlZ", headers=headers)#, proxies=proxies)
    content = r.content
    soup = BeautifulSoup(content, "html.parser")

因为我需要酿酒师、酒名和评级,所以我尝试了这个:

alls = []
    for d in soup.findAll('div', attrs={'class':'explorerCard__titleColumn--28kWX'}):
        
        Winery = d.find_all("a", attrs={"class":"VintageTitle_winery--2YoIr"})
        Wine = d.find_all("a", attrs={"class":"VintageTitle_wine--U7t9G"})
        Rating = d.find_all("div", attrs={"class":"VivinoRatingWide_averageValue--1zL_5"})
        num_Reviews = d.find_all("div", attrs={"class":"VivinoRatingWide__basedOn--s6y0t"})
        Stars = d.find_all("div", attrs={"aria-label":"rating__rating--ZZb_x rating__vivino--1vGCy"})

        alll=[]

        if Winery is not None:
            #print(n[0]["alt"])
            alll.append(Winery.text)

        else:
            alll.append("unknown-winery")

        if Wine is not None:
            #print(wine.text)
            alll.append(wine.text)
        else:
            alll.append("0")

        if Rating is not None:
            #print(rating.text)
            alll.append(rating.text)

        else:
            alll.append("0")
...

然后将数据放入 DataFrame:

results = []
for i in range(1, no_pages+1):
    results.append(get_data())
flatten = lambda l: [item for sublist in l for item in sublist]
df = pd.DataFrame(flatten(results),columns=['Winery','Wine','Rating','num_review', 'Stars'])
df.to_csv('redwines.csv', index=False, encoding='utf-8')

【问题讨论】:

  • 你的数据是 json 格式,wineries details。用这个替换你的url并提取json文件。您当前的代码不起作用,因为数据似乎在一些 javascript 代码后面。

标签: python pandas web-scraping beautifulsoup data-science


【解决方案1】:

前面的答案是正确的,但它需要设置用户代理头:

import requests
import pandas as pd

r = requests.get(
    "https://www.vivino.com/api/explore/explore",
    params = {
        "country_code": "FR",
        "country_codes[]":"pt",
        "currency_code":"EUR",
        "grape_filter":"varietal",
        "min_rating":"1",
        "order_by":"price",
        "order":"asc",
        "page": 1,
        "price_range_max":"500",
        "price_range_min":"0",
        "wine_type_ids[]":"1"
    },
    headers= {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"
    }
)
results = [
    (
        t["vintage"]["wine"]["winery"]["name"], 
        f'{t["vintage"]["wine"]["name"]} {t["vintage"]["year"]}',
        t["vintage"]["statistics"]["ratings_average"],
        t["vintage"]["statistics"]["ratings_count"]
    )
    for t in r.json()["explore_vintage"]["matches"]
]
dataframe = pd.DataFrame(results,columns=['Winery','Wine','Rating','num_review'])

print(dataframe)

您需要增加 page 字段以迭代下一个结果

【讨论】:

  • 了不起的 Bertrand,通俗易懂,真正做到了该做的事,谢谢。但是有一个问题,此代码仅返回 15 个产品,而页面上有数百个产品。关于如何更改它以获取所有产品的任何想法?
  • @DiogoSerra 您需要增加 page 字段以进行分页
  • 您是否找到有关 Vivino API 的任何文档?
【解决方案2】:

您的数据很可能在某些 JavaScript 代码后面;幸运的是,数据以 JSON 文件的形式提供。我检查了Network 标签并找到了它们。

import requests

url = "https://www.vivino.com/api/explore/explore?country_code=AU&country_codes[]=pt&currency_code=AUD&grape_filter=varietal&min_rating=1&order_by=price&order=asc&page=1&price_range_max=80&price_range_min=20&wine_type_ids[]=1"

r = requests.get(url)

# Your data:
r.json()

还有其他 JSON 文件;您可以查看浏览器的“网络”选项卡来访问它们。

【讨论】:

  • 感谢您的快速回复。但不幸的是我仍然无法获得数据。现在它给了我这个错误: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 我相信这意味着它不在 JSON 中格式
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2018-06-10
  • 2018-06-06
  • 2021-07-08
  • 2016-10-25
  • 2019-01-28
  • 1970-01-01
相关资源
最近更新 更多