Python 将使用BeautifulSoup刮取的文本打印到不带标记的数据帧
我一直在写下面的代码,让自己陷入了困境。我想做的是使用BeautifulSoup中的文本创建一个简单的数据框 我已经从Python 将使用BeautifulSoup刮取的文本打印到不带标记的数据帧,python,pandas,beautifulsoup,Python,Pandas,Beautifulsoup,我一直在写下面的代码,让自己陷入了困境。我想做的是使用BeautifulSoup中的文本创建一个简单的数据框 我已经从和标记中刮取了适用的文本,但使用find\u all意味着,当我构建数据帧并写入csv时,会包括标记。为了解决这个问题,我添加了print(p.text,end=“”)语句,但现在csv中没有写入任何内容 有人能看出我做错了什么吗 import pandas as pd import requests from bs4 import BeautifulSoup headers
和
标记中刮取了适用的文本,但使用find\u all
意味着,当我构建数据帧并写入csv时,会包括标记。为了解决这个问题,我添加了print(p.text,end=“”)
语句,但现在csv中没有写入任何内容
有人能看出我做错了什么吗
import pandas as pd
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
}
course = []
runner = []
page = requests.get('https://www.attheraces.com/tips/atr-tipsters/hugh-taylor', headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
tips = soup.find('div', class_='sticky')
for h5 in tips.find_all("h5"):
course_name = print(h5.text, end=" ")
course.append(course_name)
for p in tips.find_all("p"):
runner_name = print(p.text, end=" ")
runner.append(runner_name)
todays_tips = pd.DataFrame(
{'Course': course,
'Selection': runner,
})
print(todays_tips)
todays_tips.to_csv(r'C:\Users\*****\Today.csv')
不要使用分配给<代码>打印< /代码>,并考虑使用<代码>列表理解< /代码>。应用它应该可以获得所需的数据帧
例如:将熊猫作为pd导入
导入请求
从bs4导入BeautifulSoup
标题={
“用户代理”:“Mozilla/5.0(Windows NT 10.0;Win64;x64)AppleWebKit/537.36(KHTML,如Gecko)Chrome/68.0.3440.84 Safari/537.36”,
“接受”:“text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8”,
}
page=requests.get('https://www.attheraces.com/tips/atr-tipsters/hugh-taylor,headers=headers)
tips=BeautifulSoup(page.content,'html.parser')。find('div',class='sticky')
course=[h5.getText()用于提示中的h5.find_all(“h5”)]
runner=[p.getText()表示tips.find_all(“p”)]
todays_tips=pd.DataFrame({'Course':Course,'Selection':runner})
打印(今天的提示)
todays_tips.to_csv(“your_data.csv”,index=False)
输出:
Course Selection
0 1.00 HAYDOCK 1pt win RAINBOW JET (12-1 & 11-1 general)
1 2.50 GOODWOOD 1pt win MARSABIT (11-2 general)
和.csv
文件:
请回答您的问题,以显示所需的输出。为什么不能直接使用course.append(h5.text)
和runner.append(p.text)
?