csdn 网页代码发生变化
来源:14-12 获取和解析详情页 - 1

朗月清风
2019-06-14
csdn 网页代码发生变化
td class=“forums_topic”>
<span class="green">[置顶]</span>
<a href="/forums/placard" target="_blank" class="forums_t">社区公告・</a>
<a href="/topics/392570959" class="forums_title title_style_red title_style_bold" target="_blank" title="送!机械键盘、盖泡面Kindle、西二旗防堵山地车、真无线AirPods、找Bug雨伞,CSDN百万粉丝狂欢!">送!机械键盘、盖泡面Kindle、西二旗防堵山地车、真无线AirPods、找Bug雨伞,CSDN百万粉丝狂欢!</a>
<span class="red">[推荐]</span>
每个 td 下面 都出现 2个 a标签
这样取 topic_url = parse.urljoin(domain, tr.xpath(".//td[3]/a/@href").extract()[0])
只能取到第一个 href="/forums/placard" 的值
所以改成topic_url = parse.urljoin(domain, tr.xpath(".//td[3]/a[2]/@href").extract()[0])
能取到前两个列表的 href="/topics/392570959" 值
这样才能取出ID:392570959
运行可以取到 前两个列表的值,后边就会报错
topic_url = parse.urljoin(domain, tr.xpath(".//td[3]/a[2]/@href").extract()[0])
IndexError: list index out of range
该如何解决这个问题,有知道吗?还请告知,万分感谢!
2回答
-
只是前两条多出了“公告”“程序人生”这个a标签,后面依然是只有一个a标签的。第一个a标签的“公告”“程序人生”并没有实质内容,可以放弃掉吧?我用的这个语句“ topic_url = parse.urljoin(domain, tr.xpath(".//td[3]/a[last()]/@href").extract()[0])”只获取每一条帖子标题的最后一个a标签的内容,并且可以使得只有一个a标签的也能获取到,不报错。
232019-06-14 -
朗月清风
提问者
2019-06-14
不知道什么原因,还没有写抓取下一页的代码。
运行程序时,第1页还没抓完,不知道什么原因,会抓取第2页的内容。
def parse_list(url):
res_text = requests.get(url).text
sel = Selector(text=res_text)
all_trs = sel.xpath("//table[@class='forums_tab_table']//tr")[2:]
for tr in all_trs:
topic = Topic()
if tr.xpath(".//td[1]/span/text()").extract():
status = tr.xpath(".//td[1]/span/text()").extract()[0]
topic.status = status
if tr.xpath(".//td[2]/em/text()").extract():
score = tr.xpath(".//td[2]/em/text()").extract()[0]
topic.score = int(score)
topic_url = parse.urljoin(domain, tr.xpath(".//td[3]/a[last()]/@href").extract()[0])
topic_title = tr.xpath(".//td[3]/a[last()]/text()").extract()[0]
author_url = parse.urljoin(domain, tr.xpath(".//td[4]/a/@href").extract()[0])
author_id = author_url.split("/")[-1]
create_time = tr.xpath(".//td[4]/em/text()").extract()[0]
create_time = datetime.strptime(create_time, "%Y-%m-%d %H:%M")
answer_info = tr.xpath(".//td[5]/span/text()").extract()[0]
answer_nums = answer_info.split("/")[0]
click_nums = answer_info.split("/")[1]
last_time_str = tr.xpath(".//td[6]/em/text()").extract()[0]
last_time = datetime.strptime(last_time_str, "%Y-%m-%d %H:%M")
topic.id = int(topic_url.split("/")[-1])
topic.title = topic_title
topic.author = author_id
topic.click_nums = int(click_nums)
topic.answer_nums = int(answer_nums)
topic.create_time = create_time
topic.last_answer_time = last_time
existed_topics = Topic.select().where(Topic.id == topic.id)
if existed_topics:
topic.save()
else:
topic.save(force_insert=True)022019-06-14
相似问题