python爬取网页表格_python提取网页表格并保存为csv
时间: 2023-09-10 15:15:16 浏览: 46
可以使用Python中的BeautifulSoup库和pandas库提取网页表格并保存为csv文件。
首先,使用requests库获取网页的HTML代码,并使用BeautifulSoup库解析HTML代码,找到表格标签。
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = 'http://example.com/table.html'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table')
```
接着,使用pandas库将表格转换成DataFrame,并保存为csv文件。
```python
df = pd.read_html(str(table))[0]
df.to_csv('table.csv', index=False)
```
完整的代码如下:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = 'http://example.com/table.html'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table')
df = pd.read_html(str(table))[0]
df.to_csv('table.csv', index=False)
```
注意,以上代码仅适用于表格中没有嵌套表格的情况。如果表格中存在嵌套表格,需要做进一步处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)