Python:读取网页并从该页面提取文本

标签 python html

我正在用 Python 编写,尝试从网站获取汇率: xe.com/currency/converter (我无法发布另一个链接,抱歉 - 我能力有限) 我希望能够从此文件中获取汇率,例如英镑和美元之间的转换: 因此,我将搜索网址:“http://www.xe.com/currencyconverter/convert/?Amount=1&From=GBP&To=USD ”,然后获取打印的值“1.56371 USD”(我编写此消息时的汇率),并将该值指定为 int到一个变量,如rate_usd。 目前,我正在考虑使用BeautifulSoup模块和urllib.request模块,并请求url(“http://www.xe.com/currencyconverter/convert/?Amount=1&From=GBP&To=USD”)并使用BeautifulSoup进行搜索。目前,我正处于编码阶段:

import urllib.request
import bs4 from BeautifulSoup

def rates_fetcher(url):
    html = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(html)
    # code to search through soup and fetch the converted value
    # e.g. 1.56371
    # How would I extract this value?
    # I have inspected the page element and found the value I want to be in the class:
    # <td width="47%" align="left" class="rightCol">1.56371&nbsp;
    # I'm thinking about searching through the class: class="rightCol"
    # and extracting the value that way, but how?
url1 = "http://www.xe.com/currencyconverter/convert/?Amount=1&From=GBP&To=USD"
rates_fetcher(url1)

任何帮助将不胜感激,感谢所有花时间阅读本文的人。

附:如果我有任何拼写错误,请提前抱歉,我有点着急:s

最佳答案

听起来您的想法是正确的。

def rates_fetcher(url):
    html = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(html)
    return [item.text for item in soup.find_all(class_='rightCol')]

应该可以了...这将返回任何带有“rightCol”类的标签内的文本列表。

如果您还没有阅读Beautiful Soup documentation ,你确实应该这样做。它非常简单并且非常有用。

关于Python:读取网页并从该页面提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27261091/

相关文章:

javascript - 为什么滚动不能正常工作?

Python:没有名为unittest的模块。我怎样才能解决这个问题?

python - Django 不在 Internet Explorer 中存储 session cookie

python - self 属性不起作用python

html - 使用适当的分页符将 html/css 打印媒体显示转换为 .doc?

javascript - 使用 AngularJS 清理我的 View

html - 如何向下移动div文本框

javascript - 使用复选框的 jQuery 组合过滤器

python - 使用可重用方法和错误处理设置基于类的 View 架构

python - Pandas - 添加新的聚合功能