|
发表于 2024-5-18 09:16:55
|
显示全部楼层
抱歉,我漏掉了一个重要的步骤。在你提供的代码中,你没有传递一个有效的正则表达式给`re.compile`函数,导致无法正确匹配股票代码。此外,网页返回的内容可能经过了加密或者使用了动态加载技术,因此直接从源码中获取股票代码可能会比较困难。
为了解决这个问题,我们可以使用第三方库BeautifulSoup来帮助我们从网页中提取需要的信息。以下是修改后的代码:
- import urllib.request
- from bs4 import BeautifulSoup
- stock_codeurl="http://quote.eastmoney.com/center/gridlist.html#hs_a_board"
- def extract_stock_codes(url):
- allcodelist = []
- html = urllib.request.urlopen(url).read()
- soup = BeautifulSoup(html, 'html.parser')
- table = soup.find('table', class_='tab1')
- rows = table.find_all('tr')
- for row in rows:
- code = row.find('a').text.strip()
- allcodelist.append(code)
- return allcodelist
- alllist = extract_stock_codes(stock_codeurl)
- print(alllist)
复制代码
上述代码中,我们使用了BeautifulSoup类库来解析HTML网页,并找到包含股票代码的表格。然后,我们遍历表格的每一行,提取出股票代码并添加到`allcodelist`列表中。最后,我们打印出`alllist`,即所有股票代码的列表。
请注意,在运行代码之前,你需要通过pip安装BeautifulSoup库,可以使用以下命令进行安装:
- pip install beautifulsoup4
复制代码
希望这次能够成功获取到股票代码!如果还有其他问题,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|