Python BeautifulSoup未解析<;td>;数据正确
我正在尝试使用BeatifulSoup4和Python2.7.5进行解析。我的代码如下所示:Python BeautifulSoup未解析<;td>;数据正确,python,beautifulsoup,html-parsing,Python,Beautifulsoup,Html Parsing,我正在尝试使用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() sou
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')
url = "https://coinmarketcap.com/currencies/CRYPTO/historical-data/?
start=20171124&end=20171130"
response = urllib2.urlopen(url.replace('CRYPTO', crypto['id']))
加密被“比特币”等取代
查看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>
2017年11月30日
9906.79
10801
9202.05
10233.60
8,310,690,000
165,537,000,000
Google Chrome的Inspect window和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>
2017年11月30日
0.009829
0.013792
0.009351
0.013457
152
119,171
为什么数字不同
我使用了urllib2和请求。我使用了response.text和response.read()。我已经使用lxml和html5lib进行了解析。我尝试过不同的编码,比如iso-8859和ascii。什么都不管用
如何显示正确的数字?您需要执行以下操作:
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')
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
字符串,因为这不是工作方式,也不是Python字符串的工作方式
因此,当前代码的情况是,在调用URL中的urllib2.urlopen(…)
之前,URL中的CRYPTO
子字符串没有被替换。因此,您得到的结果来自此URL:
谢谢你指出我的白痴。是的,我知道这不是弦的工作原理。只是其中一件事。。。