Python解析网页表格 例子
时间: 2023-06-04 07:07:31 浏览: 88
可以使用Python的BeautifulSoup库和pandas库来解析网页表格,以下是一个例子:
```python
from bs4 import BeautifulSoup
import pandas as pd
import requests
url = 'http://example.com/table.html'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table')
rows = []
for tr in table.find_all('tr'):
rows.append([td.get_text(strip=True) for td in tr.find_all('td')])
df = pd.DataFrame(rows, columns=['Column 1', 'Column 2', 'Column 3'])
print(df)
```
这个例子中,我们首先使用requests库获取网页内容,然后使用BeautifulSoup库解析网页内容,找到表格元素,然后遍历每一行、每一列,将数据放到一个二维列表中。最后使用pandas库将二维列表转换为数据框,可以方便地进行数据分析和处理。
相关问题
python爬取网页表格数据
要爬取网页表格数据,可以使用 Python 中的 requests 和 BeautifulSoup 库。以下是一个简单的例子:
```
import requests
from bs4 import BeautifulSoup
url = "http://example.com/table.html" # 网页地址
response = requests.get(url) # 发送请求获取网页内容
soup = BeautifulSoup(response.content, "html.parser") # 解析网页内容
table = soup.find("table") # 找到表格元素
rows = table.find_all("tr") # 找到所有行
for row in rows:
cells = row.find_all("td") # 找到所有单元格
for cell in cells:
print(cell.text) # 输出单元格内容
```
这个例子中,我们首先使用 requests 库发送 GET 请求获取网页内容,然后使用 BeautifulSoup 库解析网页内容。接下来,我们使用 find 方法找到表格元素,再使用 find_all 方法找到所有行和单元格。最后,我们遍历每个单元格并输出其内容。
python解析html表格使用lxml库
可以使用lxml库中的html.fromstring()函数将HTML字符串转换为可供XPath和CSS选择器查询的树形结构,然后使用XPath或CSS选择器来遍历HTML表格并提取相应的数据。 举个例子:如果要使用XPath选择器提取表格中第一行第一个单元格的内容,可以使用以下代码:
``` python
from lxml import html
html_str = '<table><tr><th>Header 1</th><th>Header 2</th></tr><tr><td>Row 1, Column 1</td><td>Row 1, Column 2</td></tr><tr><td>Row 2, Column 1</td><td>Row 2, Column 2</td></tr></table>'
tree = html.fromstring(html_str)
first_cell = tree.xpath('//table/tr[1]/td[1]/text()')
print(first_cell)
```
输出应该为`[]`,因为示例html_str中的表格中没有 `<td>` 标签,而是 `<th>` 标签用于表头。你可以在XPath表达式中将第二个“td”改为“th”来修改代码以查找表头,或者使用CSS选择器。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)