抓取微博时遇到“展开全文”时,在网上搜的很多都是利用工具设置二级规则之类,尝试之后利用selenium+python直接模拟点击,抓取展开全文后的文本。
在此利用的是xpath定位元素,用别的例如CSS等也可以实现。
以下是抓取微博展开全文后文本的代码:
#判断有没有展开全文
try:
nodes[i].find_element_by_xpath(".//div[@class='feed_content wbcon']/p[@class='comment_txt']/a[@class='WB_text_opt']").is_displayed()
flag=True
except:
flag=False
#如果需要展开全文,点击后提取文本
if(flag and nodes[i].find_element_by_xpath(".//div[@class='feed_content wbcon']/p[@class='comment_txt']/a[@class='WB_text_opt']").text.startswith('展开全文c')):
nodes[i].find_element_by_xpath(".//div[@class='feed_content wbcon']/p[@class='comment_txt']/a[@class='WB_text_opt']").click()
time.sleep(1)
WBNR = nodes[i].find_element_by_xpath(".//div[@class='feed_content wbcon']/p[@node-type='feed_list_content_full']").text.encode('utf-8')
#没有展开全文,直接提取微博内容
else:
WBNR = nodes[i].find_element_by_xpath(".//div[@class='feed_content wbcon']/p[@class='comment_txt']").text.encode('utf-8')
WBNR = WBNR.decode().translate(non_bmp_map)
print(WBNR)
学习中,欢迎交流讨论,谢谢~