def get_detail(self,page_source): result = [] htmls = etree.HTML(page_source) count = htmls.xpath('//*[@id="pl_feedlist_index"]/div[2]/div') temp="" list_1 = [] creat_time ="".join(htmls.xpath('//*[@id="pl_feedlist_index"]/div[2]/div[1]/div/div[1]/div[2]/div[2]/a[1]/text()')).strip(" ").strip("\n").strip("\u3000").strip("\u200b") user_name ="".join(htmls.xpath('//*[@id="pl_feedlist_index"]/div[2]/div[1]/div/div[1]/div[2]/div[1]/div[2]/a/text()')).strip(" ").strip("\n").strip("\u3000").strip("\u200b") title ="".join(htmls.xpath('//*[@id="pl_feedlist_index"]/div[2]/div[1]/div/div[1]/div[2]/p[1]/a[1]/text()')).strip(" ").strip("\n").strip("\u3000").strip("\u200b") # text ="".join(htmls.xpath('//*[@id="pl_feedlist_index"]/div[2]/div[1]/div/div[1]/div[2]/p[2]/text()')).strip(" ").strip("\n").strip("\u3000").strip("\u200b") text ="".join(htmls.xpath('//*[@id="pl_feedlist_index"]/div[2]/div/div/div[1]/div[2]/p/text()')).strip(" ").strip("\n").strip("\u3000").strip("\u200b") list_1 =[str(creat_time),str(user_name),str(title),str(text)] result.append(list_1) titles=full3+'\\'+user_name+'.txt' f = open(titles,'a',encoding='utf-8',newline='') f.write(str(creat_time)+"\n") f.write(str(user_name)+"\n") f.write(str(title)+"\n") for i in range( 0, len(text), 80 ): temp+=text[i:i+80]+"\n"
时间: 2024-03-07 16:51:31 浏览: 29
这段代码看起来像是用来从网页源代码中提取特定信息的。具体来说,它首先使用XPath语法来定位页面中的特定元素,例如用户名称、发布时间、标题和正文。然后,它将这些信息格式化为一个列表,并将其附加到结果列表中。接下来,它将这些信息写入一个文本文件中,其中文本被格式化为每80个字符一行。这个函数似乎是用来将微博的详细内容保存到本地文件中。
相关问题
运行这段代码import requests from bs4 import BeautifulSoup import pprint import json def download_all_htmls(): """ 下载所有列表页面的HTML,用于后续的分析 """ htmls=[] for idx in range(24): url=f"https://www.utusan.com.my/page/{idx+1}" print("craw heml:",url) r=requests.get(url) if r.status_code !=250: raise Exception("error") htmls.append(r.text) return htmls htmls=download_all_htmls() htmls[0],并找出错误优化代码
这段代码中有几个错误需要优化:
1. 在判断请求状态码时,应该是 `if r.status_code != 200:` 而不是 `if r.status_code != 250:`。
2. 在函数 `download_all_htmls()` 中,`return htmls` 应该在 for 循环外面,而不是在循环内部。否则,只会下载第一个页面的 HTML。
优化后的代码如下:
```
import requests
from bs4 import BeautifulSoup
import pprint
import json
def download_all_htmls():
"""下载所有列表页面的HTML,用于后续的分析"""
htmls = []
for idx in range(24):
url = f"https://www.utusan.com.my/page/{idx+1}"
print("craw html:", url)
r = requests.get(url)
if r.status_code != 200:
raise Exception("error")
htmls.append(r.text)
return htmls
htmls = download_all_htmls()
print(htmls[0])
```
import requests from bs4 import BeautifulSoup import pprint import json def download_all_htmls(): """下载所有列表页面的HTML,用于后续的分析""" htmls = [] for idx in range(24): url = f"https://www.utusan.com.my/page/{idx+1}" print("craw html:", url) r = requests.get(url) if r.status_code != 200: raise Exception("error") htmls.append(r.text) return htmls htmls = download_all_htmls() print(htmls[0])为这段代码添加一个伪装浏览器爬取,防止反爬代码
可以在请求头中添加 `User-Agent` 字段来伪装浏览器,以防止被反爬代码检测到。具体代码如下:
```
import requests
from bs4 import BeautifulSoup
import pprint
import json
def download_all_htmls():
"""下载所有列表页面的HTML,用于后续的分析"""
htmls = []
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
for idx in range(24):
url = f"https://www.utusan.com.my/page/{idx+1}"
print("craw html:", url)
r = requests.get(url, headers=headers)
if r.status_code != 200:
raise Exception("error")
htmls.append(r.text)
return htmls
htmls = download_all_htmls()
print(htmls[0])
```
在这个例子中,我们添加了一个 `headers` 字典,它包含一个 `User-Agent` 字段,它模拟了一个常见的浏览器的用户代理字符串。这个字符串告诉服务器我们正在使用一个浏览器来访问网站,而不是一个脚本。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)