以下是一个示例代码,可以遍历数据框的URL列,并解析出HTML标签:
import pandas as pd
import requests
from bs4 import BeautifulSoup
# 创建一个示例数据框
data = {'URL': ['http://example.com', 'http://example.com']}
df = pd.DataFrame(data)
# 定义一个函数,用于解析HTML标签
def parse_html(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
tags = soup.find_all('a') # 解析出所有标签
for tag in tags:
print(tag.text) # 打印标签的文本内容
# 遍历URL列并解析HTML标签
for url in df['URL']:
parse_html(url)
在上述示例中,我们使用了pandas库创建了一个带有URL列的数据框。然后,我们定义了一个名为parse_html
的函数,该函数接受一个URL作为参数,并使用requests库获取网页的内容。然后,我们使用BeautifulSoup库将网页内容解析为一个BeautifulSoup对象,并使用find_all
方法查找所有标签。最后,我们遍历URL列,并对每个URL调用
parse_html
函数进行解析。
上一篇:遍历数据框的Python代码进行CoreNLP情感分析
下一篇:遍历数据框的行