【问题标题】:Problems scraping specific content from a DIV - BeautifulSoup从 DIV 中抓取特定内容的问题 - BeautifulSoup
【发布时间】:2015-02-14 17:18:59
【问题描述】:

我正在刮这个URL

我想像这样抓取所有餐厅,以便在单独的变量中获得餐厅名称菜肴类型和营业时间,但我不知道如何迭代它们

您可以从链接中看到餐厅 RESTAURANT DU CASINO IVORYLA STUB DU CASINO 在同一个 div div.infos-restos 中,这就是为什么我要遍历 h3s 然后让 next_siblings 进入以获取 Type of cuisine

这是我的代码

for rests in dining_soup.select("div.infos-restos"):

        for rest in rests.select("h3"):
            print("            Rest Name: "+rest.text)
            print(rest.next_sibling.next_sibling.next_sibling.next_sibling.string)

另一个问题 :) :print(rest.next_sibling.next_sibling.next_sibling.next_sibling.string) 行打印完整的 HTML。如何只获取文本?

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    我建议你使用lxml

    beautifulsoup 不支持xpath
    在我看来,使用xpath从 DOM 中提取数据要简单得多

    这是你的做法:

    from lxml import etree
    import requests
    
    url = 'http://www.accorhotels.com/gb/hotel-5548-mercure-niederbronn-hotel/restaurant.shtml'
    res = requests.get(url)
    
    tree = etree.HTML(res.content)  
    rest_name_xpath = '//div[@class="infos-restos"]/div[@class="detail-resto"]/following-sibling::h3'
    
    for item in tree.xpath(rest_name_xpath):
        print item.text
    

    输出:

    RESTAURANT DU CASINO IVORY
    BAR DES MACHINES A SOUS
    

    ps: 这个网站的html写得不好,没有适当的结构。这就是为什么xpath 又长又丑的原因

    【讨论】:

    • 支持the html of this site is badly written ..我也有同样的感觉
    猜你喜欢
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    相关资源
    最近更新 更多