import requests import re url='https://bbs.hcbbs.com' html=requests.get(url) html.encoding='GBK' #读取网页源码 reg=r'<a href="(.*?)" title=".*?" target="_blank">(.*?)</a>' #写出所需要的正则表达式 titre=re.compile(reg,re.I) #创建正则表达式对象 urls=titre.findall(html.text) print(urls) f=open('D://aaaaa.csv','a') for titu in urls: f.write(titu[0]+','+titu[1]+'\n') #csv文件以逗号分隔 f.close() 写出该段代码的设计步骤
时间: 2024-03-31 22:37:28 浏览: 28
这段代码的设计步骤如下:
1. 导入 requests 和 re 模块。
2. 定义需要爬取的网页 URL。
3. 使用 requests 模块获取网页源码,并将其编码方式设置为 GBK。
4. 编写正则表达式,用于匹配网页中的目标信息。
5. 使用 re 模块创建正则表达式对象。
6. 使用 findall 方法,从 html.text 中匹配出所有符合正则表达式的信息,并将其保存到 urls 列表中。
7. 打开一个 CSV 文件,并以追加模式写入数据。
8. 遍历 urls 列表中的元素,将其第一项和第二项以逗号分隔的形式写入 CSV 文件中。
9. 关闭 CSV 文件。
相关问题
帮我检查下下面的代码:import requests url = ['https://www.tupianzj.com/bizhi/DNmeinv/'] html = requests.get(url=url) print(html)
这段代码有一些问题,具体如下:
1. `url`应该是一个字符串而不是一个列表。可以将`url`改为`url = 'https://www.tupianzj.com/bizhi/DNmeinv/'`。
2. 在使用`requests.get()`方法时,需要传入一个字典类型的参数,而不是直接传入一个URL字符串。可以将`requests.get(url=url)`改为`requests.get(url)`。
3. 最后一行的`print()`方法只会输出`Response [200]`,这并不是我们想要的结果。可以使用`print(html.text)`来输出网页的源代码。
修改后的代码如下:
```
import requests
url = 'https://www.tupianzj.com/bizhi/DNmeinv/'
html = requests.get(url)
print(html.text)
```
帮我把下面的代码添加请求头:import requests url = 'https://www.tupianzj.com/bizhi/DNmeinv/' html = requests.get(url=url) print(html.text)
import requests
url = 'https://www.tupianzj.com/bizhi/DNmeinv/'
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 Edge/16.16299',
'Referer': 'https://www.tupianzj.com/',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive'
}
html = requests.get(url=url, headers=headers)
print(html.text)
相关推荐
![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)
![](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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)