大佬教程收集整理的这篇文章主要介绍了Python/BeautifulSoup 脚本在 CSV 中没有返回结果,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 Python 新手(以及一般编码),我正在尝试编写一个脚本,该脚本将从给定的 URL 中抓取所有 <p>
标签,然后使用它们创建一个 CSV 文件。它似乎运行正常,但它创建的 CSV 文件中没有任何数据。下面是我的代码:
import requests
r = requests.get('@R_944_10107@s://seekingAlpha.com/amp/article/4420423-chipotle-mexican-grill-inc-s-cmg-ceo-brian-niccol-on-q1-2021-results-earnings-call-transcript')
from bs4 import BeautifulSoup
soup = BeautifulSoup(r.text,'HTMl.parser')
results = soup.find_all('<p>')
records = []
for result in results:
Comment = result.find('<p>').text
records.append((Comment))
import pandas as pd
df = pd.DataFrame(records,columns=['Comment'])
df.to_csv('CMG_test.csv',index=false,enCoding='utf-8')
print('finished')
非常感谢任何帮助!
首先,您需要将 CSS 选择器传递给 BeautifulSoup 方法。 <p>
不是选择器。 p
是。因此,为了找到所有 p 标签,您需要在汤上使用 find_all
方法,如下所示:
results = soup.find_all('p')
Take a look at this page for more info on the CSS SELEctors.
其次,在对结果的迭代中,您不需要重新找到标签。您可以通过 result.text
简单地提取文本。
所以,如果你像下面这样重写你的代码:
import requests
r = requests.get('@R_944_10107@s://seekingalpha.com/amp/article/4420423-chipotle-mexican-grill-inc-s-cmg-ceo-brian-niccol-on-q1-2021-results-earnings-call-transcript')
from bs4 import BeautifulSoup
soup = BeautifulSoup(r.text,'html.parser')
results = soup.find_all('p')
records = []
for result in results:
Comment = result.text
records.append(Comment)
import pandas as pd
df = pd.DataFrame(records,columns=['Comment'])
df.to_csv('CMG_test.csv',index=false,encoding='utf-8')
print('finished')
您会发现您的 csv 中充满了您要查找的内容。
以上是大佬教程为你收集整理的Python/BeautifulSoup 脚本在 CSV 中没有返回结果全部内容,希望文章能够帮你解决Python/BeautifulSoup 脚本在 CSV 中没有返回结果所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。