Python使用BeautifulSoup解析出现
无法消除问题

最近看小说,总有奇奇怪怪的广告出现,于是想要抓下来慢慢看,于是开始动手:

resp = requests.post(URL + endPoint,headers = headers)
      soup = bs(resp.content,'html.parser',from_encoding = 'utf-8')
      #抓取文章内容
      tag = soup.find('div',id='nr')
      tagnext = soup.find('a',id = 'pb_next')
      nr = tag.get_text().encode('utf-8')
      #获取下一章地址
      match = re.match('.*html$',tagnext['href'])
      if match is None:
          return (nr,None)
      return (nr,match.string)

写完后我想,终于可以看小说了,于是我开心的点开我的文件

Python使用BeautifulSoup解析出现<br/>无法消除问题_第1张图片
F361CE6F-5013-4E2F-9677-443644AD7C48.png

发现上面有好多^M的,看了一下html之后发现,每一行都有一个
标签来换行.
于是查找解决方法,最终发现了一个很好用的方法

只需要更改一个小地方,在get_text()中用\n替换掉
print (tag.get_text('\n','
'))
Python使用BeautifulSoup解析出现<br/>无法消除问题_第2张图片
B2D76A90-E179-41C6-BB2D-B9E8B785874E.png

问题解决.

scrapy xpath 去除'
'

response = response.replace(body=response.body.replace(b'
', b'\n'))

感谢收看,欢迎拍砖

你可能感兴趣的:(Python使用BeautifulSoup解析出现
无法消除问题)