【发布时间】: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