gpt4 book ai didi

html - 解码在 python 2.7 中无法正常工作

转载 作者:行者123 更新时间:2023-11-28 04:10:44 26 4
gpt4 key购买 nike

我正在尝试制作一个使用网络爬取来检索股票信息的程序,但不知何故该程序无法解码网页。我希望这段代码严格适用于 python 2。

import urllib2
import re

stock=str(raw_input("Give the stock name"))

url = "https://www.google.com/finance?q="

req = urllib2.Request(url)
response = urllib2.urlopen(req)
data = str(response.read())

data1 = data.decode('utf-8')

print(data)
m = re.search('meta itemprop="price"',data1)
start = m.start()
end = start+50
newString = data1[start:end]
m=re.search('content="',newString)
start = m.end()
newString1 = newString[start:]
m = re.search("/",newString1)
start=0
end=m.end()-3
final= newString1[0:end]

print(final)

最佳答案

这不是对您问题的直接回答,而是一个建议。尝试使用 beautifulsoup python 库。它具有许多用于网络抓取和爬行的可用功能以及其他功能,并且可以处理您在问题中尝试实现的大部分内容,并且与所有 python 版本兼容。

转到 https://pypi.python.org/pypi/beautifulsoup4用于文档。

一个示例是;

import BeautifulSoup, urllib

url = 'http://www.py4inf.com/code/romeo.txt'
html = urllib.urlopen(url).read()
soup = BeautifulSoup.BeautifulSoup(html)
x = soup('a')

print x

关于html - 解码在 python 2.7 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42732710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com