【问题标题】:lxml scraping overwrite error due to missing element由于缺少元素,lxml 抓取覆盖错误
【发布时间】:2018-12-13 15:43:59
【问题描述】:

我目前正在尝试从 imdb 中抓取用户评论信息,包括用户给出的星级评分、评论标题和评论文本本身。 但是,当评论中没有给出星级时,我似乎遇到了问题。我的代码似乎覆盖了星级,并假设从没有给出星级的那一刻起,页面上没有给出进一步的星级。 缺少星级时,我只想显示“无输入”这句话。

这是我的代码:

import lxml
from lxml import html
import requests
headers= {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36"}
page = requests.get('https://www.imdb.com/title/tt0108052/reviews?ref_=tt_ql_3', headers=headers)
tree = html.fromstring(page.content)


x=tree.xpath('//div[@class="lister-item-content"]')
for index in range(len(x)):    

    Title='###Title:',(tree.xpath('//a[@class="title"]')[index]).text_content()
    Author='###Author:',(tree.xpath('//span[@class="display-name-link"]')[index]).text_content()
    Text='###Text:', (tree.xpath('//div[@class="text show-more__control"]')[index]).text_content()
    if (tree.xpath('.//div[@class="ipl-ratings-bar"]')[index]) in (tree.xpath('.//div[@class="lister-item-content"]')[index]):
        Stars=(tree.xpath('//div[@class="ipl-ratings-bar"]/span[1]/span[1]')[index]).text_content()
    else:
        Stars=('no input')
    if index <5:
        print([('###Index:', index), Stars, Title])

这是我得到的当前输出:

[('###Index:', 0), '10', ('###Title:', ' Bring me the head of Hitler n Himmler.\n')]
[('###Index:', 1), 'no input', ('###Title:', ' The most shattering film of all time.\n')]
[('###Index:', 2), 'no input', ('###Title:', " Excellent - Spielberg's Best\n")]
[('###Index:', 3), 'no input', ('###Title:', ' Vehement\n')]
[('###Index:', 4), 'no input', ('###Title:', " don't take this personally\n")]

索引 0 和 1 当前为“10”和“无输入”。但是,索引 3、4 和 5 应分别具有“9”、“10”和“7”星级。为什么在第一次丢失星级后,星级会被“无输入”覆盖,即使这是不正确的?

【问题讨论】:

    标签: python web-scraping lxml


    【解决方案1】:

    为什么不尝试如下填充结果而不是索引。我希望它能解决您当前的问题:

    import requests
    from lxml.html import fromstring
    
    link = 'https://www.imdb.com/title/tt0108052/reviews?ref_=tt_ql_3'
    
    page = requests.get(link, headers= {"User-Agent":"Mozilla/5.0"})
    tree = fromstring(page.content)
    for item in tree.xpath('//div[contains(@class,"imdb-user-review")]'):    
        title = item.xpath('.//a[@class="title"]')[0].text.strip()
        author = item.xpath('.//span[@class="display-name-link"]/a')[0].text.strip()
        text = item.xpath('.//div[starts-with(@class,"text")]')[0].text.strip()
        stars = (item.xpath('.//span[@class="rating-other-user-rating"]')+['N\A'])[0]
        if stars != "N\A": 
            stars = stars.text_content().strip()
        else:
            stars = "N\A"
        print(f'{title}\n{author}\n{text}\n{stars}\n')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-23
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 2017-02-07
      • 2012-01-06
      • 2013-11-26
      相关资源
      最近更新 更多