zna*_*wca 5 python beautifulsoup
我想从网站http://www.x-rates.com/table/?from=USD&amount=1(它是货币兑换网站)废弃数据.
我想从表中得到"欧元"字样,但我得到空列表.这是我的代码:
from bs4 import BeautifulSoup
import requests
res = requests.get('http://www.x-rates.com/table/?from=USD&amount=1')
soup = bs4.BeautifulSoup(res.text, 'html.parser')
hehe = soup.select('table.ratesTable:nth-child(4) > tbody:nth-child(2) > tr:nth-child(1) > td:nth-child(1)')
print hehe
Run Code Online (Sandbox Code Playgroud)
我也试过这个:
hehe = soup.select('table.ratesTable + table.ratesTable + table.ratesTable + table.ratesTable table.ratesTable + tbody + tbody + tbody + tr + tr + td + td')
Run Code Online (Sandbox Code Playgroud)
但仍然没有.我应该改变什么?
如果你想清理桌子,Pandas 会更好。对于您的用例,我们只有几行代码:
import pandas as pd
df_all = pd.read_html('http://www.x-rates.com/table/?from=USD&amount=1',header=0,attrs={'class':"tablesorter ratesTable"})
df = pd.concat(df_all).reset_index(drop=True)
df.columns = ['currency','to_usd','inv_usd']
df
currency to_usd inv_usd
0 Argentine Peso 15.358513 0.065110
1 Australian Dollar 1.388332 0.720289
2 Bahraini Dinar 0.376989 2.652594
3 Botswana Pula 11.219075 0.089134
4 Brazilian Real 3.927585 0.254609
...
Run Code Online (Sandbox Code Playgroud)
如果您只关心欧元,则可以使用以下命令从数据框中获取该行
df[df.currency=='Euro']
currency to_usd inv_usd
14 Euro 0.908652 1.100532
Run Code Online (Sandbox Code Playgroud)
另外,你还可以这样做:
df[df.currency=='Euro'].to_usd.values[0]
0.908652
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用以下代码通过 bs 访问表 html。但最终,您需要将其放入 pandas 之类的东西中来处理它,所以我建议使用上面的方法。
from bs4 import BeautifulSoup
import requests
page = requests.get('http://www.x-rates.com/table/?from=USD&amount=1')
soup = BeautifulSoup(page.content, 'html.parser')
tab_html = soup.find_all('table', {'class':"tablesorter ratesTable"})
tab_html
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
220 次 |
| 最近记录: |