【问题标题】:Extracting data to an Excel file from <html> body in Python从 Python 中的 <html> 正文中提取数据到 Excel 文件
【发布时间】:2019-06-02 16:10:34
【问题描述】:

我正在使用mechanize 从我订阅的受密码保护的网站获取一些数据。

我可以使用代码访问网站的 .txt:

import mechanize
from bs4 import BeautifulSoup

username = ''
password = ''

login_post_url = "http://www.naturalgasintel.com/user/login"
internal_url = "https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/2018/12/20181221td.txt"

browser = mechanize.Browser()
browser.open(login_post_url)
browser.select_form(nr = 1)
browser.form['user[email]'] = username
browser.form['user[password]'] = password
browser.submit()

response = browser.open(internal_url)
print response.read().decode('utf-8').encode('utf-8')

这会打印出我想要的格式(减去数据点之间的额外空白):

Point Code      Issue Date      Trade Date      Region  Pricing Point   Low     High    Average Volume  Deals   Delivery Start Date     Delivery End Date
STXAGUAD        2018-12-21      2018-12-20      South Texas     Agua Dulce                                              2018-12-21      2018-12-21
STXFGTZ1        2018-12-21      2018-12-20      South Texas     Florida Gas Zone 1      3.580   3.690   3.660   30      7       2018-12-21      2018-12-21
STXNGPL 2018-12-21      2018-12-20      South Texas     NGPL S. TX                                              2018-12-21      2018-12-21
STXTENN 2018-12-21      2018-12-20      South Texas     Tennessee Zone 0 South  3.460   3.580   3.525   230     42      2018-12-21      2018-12-21
STXTETCO        2018-12-21      2018-12-20      South Texas     Texas Eastern S. TX     3.510   3.575   3.530   120     28      2018-12-21      2018-12-21
STXST30 2018-12-21      2018-12-20      South Texas     Transco Zone 1  3.505   3.505   3.505   9       2       2018-12-21      2018-12-21
STX3PAL 2018-12-21      2018-12-20      South Texas     Tres Palacios   3.535   3.720   3.630   196     24      2018-12-21      2018-12-21
STXRAVG 2018-12-21      2018-12-20      South Texas     S. TX Regional Avg.     3.460   3.720   3.570   584     103     2018-12-21      2018-12-21

但我想读取所有这些数据并将其写入 Excel 文件。

我尝试使用soup = BeautifulSoup(response.read().decode('utf-8').encode('utf-8') 将其分解为实际文本,除了html 形式之外,它给了我相同的东西:

<html><body><p>Point Code\tIssue Date\tTrade Date\tRegion\tPricing Point\tLow\tHigh\tAverage\tVolume\tDeals\tDelivery Start Date\tDelivery End Date\nSTXAGUAD\t2018-12-21\t2018-12-20\tSouth Texas\tAgua Dulce\t\t\t\t\t\t2018-12-21\t2018-12-21\nSTXFGTZ1\t2018-12-21\t2018-12-20\tSouth Texas\tFlorida Gas Zone 1\t3.580\t3.690\t3.660\t30\t7\t2018-12-21\t2018-12-21\nSTXNGPL\t2018-12-21\t2018-12-20\tSouth Texas\tNGPL S. TX\t\t\t\t\t\t2018-12-21\t2018-12-21\nSTXTENN\t2018-12-21\t2018-12-20\tSouth Texas\tTennessee Zone 0 South\t3.460\t3.580\t3.525\t230\t42\t2018-12-21\t2018-12-21\nSTXTETCO\t2018-12-21\t2018-12-20\tSouth Texas\tTexas Eastern S. TX\t3.510\t3.575\t3.530\t120\t28\t2018-12-21\t2018-12-21\

我可以开始考虑从 soup 变量中剥离 html 标记,但有没有办法更轻松地剥离这些数据?

【问题讨论】:

  • 你需要使用python 2.7吗?老实说,使用 csv 并尝试使用 utf-8 是一个很大的麻烦。从经验上讲,如果您可以进行切换,现在只会节省大量时间和头痛。
  • 现在没有了。我使用 2.7 只是因为一个旧脚本使用了 twill 包 - 但它造成的损害大于好处。我可以使用 3.x
  • 太棒了,2 秒内我会为您找到答案 :) 来自埃德蒙顿的问候!
  • 好的,我为你更新了答案。这应该会让你走上你想要去的地方。
  • 艾伯塔人团结起来!

标签: python html python-2.7 parsing beautifulsoup


【解决方案1】:

既然你已经表明你可以使用python3,我建议以下步骤:

下载 Anaconda

Download Anaconda Python for you OS

从更广泛的角度来看,Anaconda 对数据科学和数据检索具有最佳的原生支持。您将下载 python 3.7,它为您提供了 Python 2.7 的所有功能(一些更改),而不会让人头疼。对您而言,重要的是 python 2.7 在使用 utf-8 时会让人头疼。这将解决很多这些问题:

安装你的库

安装 Anaconda 后(如果您在安装期间选择退出,则在将 conda.exe 设置为系统 PATH 变量 which takes 2 minutes 后),您需要安装软件包。从你的脚本来看,它看起来像这样:

conda install mechanize,bs4,requests,lxml -y

请耐心等待 - conda 可能需要 2-10 分钟才能“解决您的环境”,然后再安装。

使用 Pandas 解析数据

这里有 2 个选项供您尝试,它们取决于您对正在抓取的 html 格式的幸运程度

import pandas as pd # This can go at the top with the other imports.

使用 pandas.read_html()

response = browser.open(internal_url)
html = response.read().decode('utf-8').encode('utf-8')
df = pd.read_html(html)
print(df) # This should give you a preview of *fingers-crossed* each piece of data in it's own cell.
pd.to_csv(df,"naturalgasintel.csv")

使用 pandas.read_data()

response = browser.open(internal_url)
soup = BeautifulSoup(str(innerHTML.encode('utf-8').strip()), 'lxml')
# If your data is embedded within a nested table, you may need to run soup.find() here
df = pd.DataFrame.from_records(soup)
print(df) # This should give you a preview of *fingers-crossed* each piece of data in it's own cell.
pd.to_csv(df,"naturalgasintel.csv")

希望对您有所帮助! Pandas 是一个出色的库,可以直观地解析您的数据。

【讨论】:

  • 我知道我可能可以使用requests 之类的东西,但我不得不绕过它,因为它对我不起作用。不幸的是,mechanize 是唯一给我想要的东西的包,它只适用于 Python 2.7 环境。此外,当使用pd.read_html() 时,参数必须是可读的表格形式,但我的垃圾只是一个大字符串!当。所以当我使用 read
猜你喜欢
  • 2021-06-06
  • 2019-01-17
  • 2021-06-01
  • 2017-12-30
  • 2019-06-10
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多