BeautifulSoup无法正确解析<td>数据

费伯费多

我正在尝试使用BeatifulSoup4和Python2.7.5来解析此页面我的代码如下所示:

url = "https://coinmarketcap.com/currencies/CRYPTO/historical-data/?
      start=20171124&end=20171130"
url.replace('CRYPTO', crypto['id'])
response = urllib2.urlopen(url)

data = response.read()
soup = BeautifulSoup(data, 'html5lib')

trs = soup.find(id="historical-data").findAll('tr')

其中CRYPTO被“比特币”等替代。

查看PyCharm中的变量,除了表中的数据外,其他一切看起来都不错。而不是看到此:

<tr class="text-right">
<td class="text-left">Nov 30, 2017</td>
<td>9906.79</td>
<td>10801.00</td>
<td>9202.05</td>
<td>10233.60</td>
<td>8,310,690,000</td>
<td>165,537,000,000</td>
</tr>

这就是Google Chrome浏览器的Inspect窗口和curl向我显示的内容,BeautifulSoup向我显示了以下内容:

<tr class="text-right">
<td class="text-left">Nov 30, 2017</td>
<td>0.009829</td>
<td>0.013792</td>
<td>0.009351</td>
<td>0.013457</td>
<td>152</td>
<td>119,171</td>
</tr>

为什么数字不同?

我已经使用了urllib2和请求。我使用过response.text和response.read()。我已经使用lxml和html5lib进行了解析。我尝试了不同的编码,例如iso-8859和ascii。没用。

如何获得正确的数字以显示?

sideshowbarker

您需要改为执行以下操作:

url = "https://coinmarketcap.com/currencies/CRYPTO/historical-data/?
      start=20171124&end=20171130"
response = urllib2.urlopen(url.replace('CRYPTO', crypto['id']))

…或更明确地说明正在发生的事情:

url = "https://coinmarketcap.com/currencies/CRYPTO/historical-data/?
      start=20171124&end=20171130"
newurl = url.replace('CRYPTO', crypto['id'])
response = urllib2.urlopen(newurl)

…因为您的代码现在已经存在,所以您url.replace('CRYPTO', crypto['id'])自己不会更改任何内容;相反,它只会创建一个新字符串,但不会对该新字符串执行任何操作。

您的代码没有更改url字符串,因为这不是string.replace(…)工作原理,也不是Python字符串如何工作。

因此,当前代码正在发生的事情是,在CRYPTO调用URL之前,不会替换URL中的子字符串urllib2.urlopen(…)因此,您从以下URL获得的结果是:

https://coinmarketcap.com/currencies/CRYPTO/historical-data/?start=20171124&end=20171130

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章