【问题标题】:Scraping a page + click on its href and takes hrefs data抓取页面+单击其href并获取hrefs数据
【发布时间】:2018-05-22 08:14:56
【问题描述】:

我正在尝试废弃一个页面并获取标签中的 hrefs 数据,但我无法获得结果。这是我学校的作业。 有人可以帮我解决这个问题吗?

这是我的代码:

from bs4 import BeautifulSoup
import re
import requests

for i in range (1,5):
    base_url = 'https://www.leboncoin.fr/locations'
    url = 'https://www.leboncoin.fr/locations/1152669519.htm?ca=22_s'
    res = requests.get(url)
    soup = BeautifulSoup(res.text)

    locations = []

    links = soup.find_all(['li','a'], href=re.compile('.*\/locations\/+(i)+'))

    for l in links:
        full_link = base_url + l['href']
        titre = l[['li', 'section', 'h2']].strip()
        res = requests.get(full_link)
        soup = BeautifulSoup(res.text)
        loyer = soup.find(['h2','span'], attrs={"class": "value\^((?![A-Z]).)*$"})
        loyers = loyer.text
        ville = soup.find(['h2','span'], attrs={"class": "value", "itemprop": "adresse"})
        villes = ville.text
        surface = soup.find(['h2','span'], attrs={"class": "clearfix", "calss": "value"})
        surfaces = surface.text
        description = soup.find('p', attrs={"class": "value", "itemprop": "description"})
        descriptions = description.text
        shops.append(titre, loyers, villes, surfaces, descriptions)

    print(locations)

我得到了这样的结果:

[]
[]
[]
[]

提前感谢您的回答。

【问题讨论】:

  • 您在代码中的任何时候都不会向locations 附加任何内容,为什么打印时不能为空?
  • 是的,我忘了修改这个,因为我拿了一个之前解决的问题并针对我的情况进行了调整。 Scraping data from href 但我没有得到任何结果。
  • 这就是我想说的,你没有得到任何结果,因为你从来没有向locations 添加任何东西。如果您从不向其中添加任何内容,那么您从其他地方复制多少其他代码都没有关系,locations 仍然是空的。您希望locations 包含什么内容?
  • 我希望这些位置包含locations.append(shops) 但即使使用另一个人提出的以下代码,我也一无所获。

标签: python html web-scraping beautifulsoup href


【解决方案1】:

您没有在任何地方定义商店,我假设您想要一本字典。因此,请这样做:

for l in links:
    shops = {}
    full_link = base_url + l['href']
    shops['titre'] = l[['li', 'section', 'h2']].strip()
    res = requests.get(full_link)
    soup = BeautifulSoup(res.text)
    loyer = soup.find(['h2','span'], attrs={"class": "value\^((?![A-Z]).)*$"})
    shops['loyers'] = loyer.text
    ville = soup.find(['h2','span'], attrs={"class": "value", "itemprop": "adresse"})
    shops['villes'] = ville.text
    surface = soup.find(['h2','span'], attrs={"class": "clearfix", "calss": "value"})
    shops['surfaces'] = surface.text
    description = soup.find('p', attrs={"class": "value", "itemprop": "description"})
    shops['descriptions'] = description.text
    locations.append(shops)

print(locations)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 2011-10-01
相关资源
最近更新 更多