×

python requests beautifulsoup 基金 名单

抓取规模超过1000亿的基金公司名单

鹭岛小千 鹭岛小千 发表于2021-09-05 22:00:35 浏览760 评论0

抢沙发发表评论

【问题描述】如何抓取以下网页内规模超过1000亿的基金公司名单呢?

目标网址:

http://fund.eastmoney.com/company/default.html

目标内容:

38-1.png

【小千解答】使用requests库获取目标网页的源代码,使用beautifulsoup4库的CSS选择器提取目标网页元素。

安装两个库:

pip install requests
pip install beautifulsoup4

目标元素的定位思路:table→tbody→tr→td

38-2.png示例代码如下:

import requests
from bs4 import BeautifulSoup

url = 'http://fund.eastmoney.com/company/default.html'
res = requests.get(url)
if (res.status_code == 200):
    xqsoup = BeautifulSoup(res.content,'lxml')
    xqinfo = ''
    with open('d:/py/jijin.txt','w') as f:
        for tr in xqsoup.select('#gspmTbl tbody tr'):
            xqtds = tr.select('td')
            xqnum = xqtds[5].get_text().split()[0]
            if xqnum != '-' and float(xqnum.replace(',',''))>1000:
                xqinfo = xqtds[1].string + '\t' + xqnum + '\n'
                f.write(xqinfo)

注解:

  • res.content返回bytes类型,BeautifulSoup会自动将输入内容转换为Unicode编码,输出内容转换为utf-8编码,所以通常无需做转码加工。

  • xqtds[5].get_text()和xqtds[5].string等价。


提取效果:

38-3.png


打赏码.png


【参考资料】

  1. Requests Developer Interface

  2. Beautiful Soup 4.4.0 文档

  3. 图书《Python网络爬虫技术与实战》P122-123、P131

  4. BeautifulSoup.select 如何根据select得到得标签树继续select?


群贤毕至

访客