|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import requests
- import bs4
- headers = {
- 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
- }
- url = "http://www.xbiquge.la/0/951/827334.html"
- res = requests.get(url=url, headers=headers)
- res.encoding = "utf-8"
- soup = bs4.BeautifulSoup(res.text, "html.parser")
- targets = soup.find_all("div", id="content")
- for each in targets:
- print(each)
- for i in each:
- print(i)
复制代码
为什么要在加个for循环才能看到小说的内容?
因为 soup.find_all("div", id="content") 提取到的是所有 div 标签下 id 属性为 content 的 bs4 对象数据,你需要 for 循环将对象中的内容重新提取使用才行
帮你稍微改了下代码,去掉标签保留文本内容了:
- import requests
- import bs4
- headers = {
- 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
- }
- url = "http://www.xbiquge.la/0/951/827334.html"
- res = requests.get(url=url, headers=headers)
- res.encoding = "utf-8"
- soup = bs4.BeautifulSoup(res.text, "html.parser")
- targets = soup.find_all("div", id="content")
- for each in targets:
- for i in each:
- if i.string == None:
- continue
- print(i.string)
复制代码
|
|