python如何读取网页中的数据

2021-11-03 社会 115阅读

用BeautifulSoup这类解析模块:

  1. BeautifulSoup是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parsetree);

  2. 它提供简单又常用的导航(navigating),搜索以及修改剖析树的操作;

  3. 用urllib或者urllib2(推荐)将页面的html代码下载后,用beautifulsoup解析该html;

  4. 然后用beautifulsoup的查找模块或者正则匹配将你想获得的内容找出来,就可以进行相关处理了,例如:

    from BeautifulSoup import BeautifulSoup
    html = 'test

    test body

    '
    soup = BeautifulSoup(html)
    soup.contents[0].name
    # u'html'
    soup.comtents[0].contents[0].name
    # u'head'
    head = soup.comtents[0].contents[0]
    head.parent.name
    # u'html'
    head.next
    # u'test
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com