Python 抓取在线社交论坛-无法获取日期
我目前正在努力清理这个在线论坛: 正如你所看到的,主页是一个包含所有帖子的列表页面,然后我必须点击每个帖子才能获得完整内容和回复。我需要的每个帖子的信息是:标题、作者、日期和帖子的消息内容。我还需要为每个帖子的每个回复提供相同的信息(作者、日期和内容) 到目前为止,我遇到的问题是,我可以在网站上看到发布日期,但不能使用Scrapy。以下是元素检查: 但在Scrapy shell中,日期文本应该是一个空白: 我尝试过许多CSS和Xpath方法,但都没有效果 最后,我希望生成的CSV文件在第一行包含原始帖子信息,然后在下一行包含回复信息。这样我就可以跟踪交互。并且,文章标题或其他消息ID将是公共标识符。以下是一个例子: 好的,到目前为止,这是我的痒蜘蛛。这是非常混乱的,因为我一直在努力解决日期问题Python 抓取在线社交论坛-无法获取日期,python,web-scraping,scrapy,Python,Web Scraping,Scrapy,我目前正在努力清理这个在线论坛: 正如你所看到的,主页是一个包含所有帖子的列表页面,然后我必须点击每个帖子才能获得完整内容和回复。我需要的每个帖子的信息是:标题、作者、日期和帖子的消息内容。我还需要为每个帖子的每个回复提供相同的信息(作者、日期和内容) 到目前为止,我遇到的问题是,我可以在网站上看到发布日期,但不能使用Scrapy。以下是元素检查: 但在Scrapy shell中,日期文本应该是一个空白: 我尝试过许多CSS和Xpath方法,但都没有效果 最后,我希望生成的CSV文件在第一行
import scrapy
围产期蜘蛛类(刮毛蜘蛛):
名称='围产期'
start_urls = ['http://www.community.whattoexpect.com/forums/postpartum-depression.html']
def parse(self, response):
for post_link in response.xpath('//*[@class="group-discussions__list__item__block"]/a/@href').extract():
link = response.urljoin(post_link)
yield scrapy.Request(link, callback=self.parse_post)
# Checks if the main page has a link to next page if True keep parsing.
next_page = response.xpath('(//a[@class="page-link"])[1]/@href').extract_first()
if next_page:
yield scrapy.Request(next_page, callback=self.parse)
def parse_thread(self, response):
original_post = response.xpath("//*[@class='__messageContent fr-element fr-view']/p/text()").extract()
title = response.xpath("//*[@class='discussion-original-post__title']/text()").extract_first()
author_name = response.xpath("//*[@class='discussion-original-post__author__name']/text()").extract_first()
timestamp = response.xpath("//*[@class='discussion-original-post__author__updated']/text()").extract_first()
replies_list = response.xpath("//*[@class='discussion-replies__list']").getall()
for reply in replies_list:
# reply content
replies = "".join(reply.xpath(".//*[@class='wte-reply__content']/p/text()").extract())
reply_author= reply.xpath("//*[@class='wte-reply__author']/text()").extract_first()
yield {
"title": title,
"post": original_post,
"author_name": author_name,
"replies": replies,
"reply_author": reply_author,
"time": timestamp
}
JS从属性数据日期在页面上呈现的可读日期。这个号码是 你可以很容易地处理它
import datetime # We need this module to deal with date
unixtimestamp = response.xpath("//*[@class='discussion-original-post__author__updated']/@data-date").extract_first() # Extracting timestamp
unixtimestamp = int(unixtimestamp)/1000 # Removing milliseconds
timestamp = datetime.datetime.utcfromtimestamp(unixtimestamp).strftime("%m/%d/%Y %H:%M")
日期以UTC为单位。如果你需要另一个时区-你必须增加一些小时或转换到另一个时区