python获取网页指定区域的内容
时间:2022-10-07 来源:未知 投稿:admin 点击:次
例:
import requests import parsel url = 'https://www.fwqzx.com/script/Python/2022/0930/1157.html' fwqzx = requests.get(url) fwqzx.encoding = 'gbk' #print(fwqzx.text) selector = parsel.Selector(fwqzx.text) #将字符串数据转换成可解析的selector对象 title = selector.css('body > div.main4 > div.m4_left.FL > h1::text').get() #css路径内容使用chrome浏览器:检查>copy>copy selector #title2 = selector.xpath('/html/body/div[5]/div[1]/h1/text()').get() #使用xpath方式获取内容 concent_list = selector.css('body > div.main4 > div.m4_left.FL > div.m4_box6::text').getall() #concent2 = selector.xpath('/html/body/div[5]/div[1]/div[5]/text()').getall() concent = ''.join(concent_list) print(title) print(concent) #将获取的数据保存到文本 with open(title + '.txt',mode='w',encoding='utf-8') as f: #with open(f'D:\\data\\{title}.txt',mode='w',encoding='utf-8') as f: //使用绝对路径保存格式 f.write(title) f.write(' ') f.write(concent)
如果您的问题仍未解决,还可以加入服务器在线技术交流QQ群:8017413寻求帮助。
相关内容