使用PYTHON从web页面捕获数据

2024-10-02 04:22:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从下面的链接捕获文本并保存它。 http://forecast.weather.gov/product.php?site=NWS&issuedby=FWD&product=RR5&format=CI&version=44&glossary=0

我只需要保存.A之后的文本,因此我不需要页面中的其他文本。此外,在页面顶部有50个不同的链接,我想从中获取所有的数据。你知道吗

我已经写了下面的代码,但它没有返回任何东西,如何才能具体得到我需要的部分?你知道吗

import urllib
import re
htmlfile=urllib.urlopen("http://forecast.weather.gov/product.php?site=NWS&issuedby=FWD&product=RR5&format=CI&version=1&glossary=0")
htmltext=htmlfile.read()
regex='<pre class="glossaryProduct">(.+?)</pre>'
pattern=re.compile(regex)
out=re.findall(pattern, htmltext)
print (out)

我还使用了以下方法返回页面的所有内容:

import urllib
file1 = urllib.urlopen('http://forecast.weather.gov/product.php?site=NWS&issuedby=FWD&product=RR5&format=txt&version=1&glossary=0')
s1 = file1.read()
print(s1)

你能帮我这么做吗?你知道吗


Tags: 文本formathttpversionsiteurllibproductgov
1条回答
网友
1楼 · 发布于 2024-10-02 04:22:59

您的正则表达式没有捕获任何内容,因为您的内容以换行符开始,并且您没有启用.来包含换行符。如果将编译行更改为

pattern=re.compile(regex,re.S)

应该有用。你知道吗

您还可以查看:

https://regex101.com

它确切地显示了你的正则表达式在做什么。当我把S旗放在右边时,它就开始正常工作了:

Image of regex working with the S flag

相关问题 更多 >

    热门问题