gpt4 book ai didi

python - 使用python从网页中读取值

转载 作者:行者123 更新时间:2023-11-28 21:22:27 25 4
gpt4 key购买 nike

我正在尝试将 html 页面中的值读入 python 脚本中的变量。我已经想出了一种使用 urllib 将页面下载到本地文件的方法,并且可以使用 bash 脚本提取值,但想在 Python 中尝试。

import urllib
urllib.urlretrieve('http://url.com', 'page.htm')

页面中有这个:

<div name="mainbody" style="font-size: x-large;margin:auto;width:33;">
<b><a href="w.cgi?hsn=10543">Plateau (19:01)</a></b>
<br/> Wired: 17.4
<br/>P10 Chard: 16.7
<br/>P1 P. Gris: 17.1
<br/>P20 Pinot Noir: 15.8-
<br/>Soil Temp : Error
<br/>Rainfall: 0.2<br/>
</div>

我需要 Wired: 行中的 17.4 值

有什么建议吗?

谢谢

最佳答案

从不使用 urlretrieve() 开始;您需要的是数据,而不是文件。

接下来,使用 HTML 解析器。 BeautifulSoup非常适合从 HTML 中提取文本。

使用 urllib2 检索页面将是:

from urllib2 import urlopen

response = urlopen('http://url.com/')

然后将数据读入BeautifulSoup:

from bs4 import BeautifulSoup

soup = BeautifulSoup(response.read(), from_encoding=response.headers.getparam('charset'))

那里的 from_encoding 部分将告诉 BeautifulSoup Web 服务器告诉您该页面使用什么编码;如果网络服务器没有指定,那么 BeautifulSoup 将为您做出有根据的猜测。

现在您可以搜索您的数据:

for line in soup.find('div', {'name': 'mainbody'}).stripped_strings:
if 'Wired:' in line:
value = float(line.partition('Wired:')[2])
print value

对于您的演示 HTML 片段,它提供:

>>> for line in soup.find('div', {'name': 'mainbody'}).stripped_strings:
... if 'Wired:' in line:
... value = float(line.partition('Wired:')[2])
... print value
...
17.4

关于python - 使用python从网页中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19175180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com