由于缺少元素,lxml 抓取覆盖错误

lxml scraping overwrite error due to missing element

我目前正在尝试从 imdb 中抓取用户评论信息,包括用户给出的星级、评论标题和评论文本本身。 但是,当评论中未给出星级时,我似乎遇到了问题。我的代码似乎覆盖了星级评级,并假设从没有给出星级评级的那一刻起,页面上就不再给出进一步的星级评级。 当缺少星级时,我只想让短语 "no input" 出现。

这是我的代码:

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”和 "no input"。但是,索引 3、4 和 5 应分别具有星级“9”、“10”和“7”。为什么在第一个缺少星级的情况下,星级被 "no input" 覆盖,即使那是不正确的?

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

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')