Python代码仅适用于标题标签,不适用于表格

标签 python python-2.7

在正则表达式中写入<title>(.+?)</title>时它正在工作,但是当此标题标签更改为 <table>(.+?)</table> 时它给出“[]”(方括号)作为输出。 我的代码是:

import urllib
import re

urls = ["http://physics.iitd.ac.in/content/list-faculty-members", "http://www.iitkgp.ac.in/commdir3/list.php?division=3&deptcode=ME","http://www.iitkgp.ac.in/commdir3/list.php?division=3&deptcode=CE"]
i = 0
regex = '<table>(.+?)</table>'
pattern = re.compile(regex)

while i< len(urls):
    htmlfile = urllib.urlopen(urls[i])
    htmltext = htmlfile.read()
    tables  = re.findall(pattern,htmltext)

    print tables
    i+=1

最佳答案

使用BeautifulSoup :

import urllib
import re

from BeautifulSoup import BeautifulSoup as bs

urls = ["http://physics.iitd.ac.in/content/list-faculty-members", 
        "http://www.iitkgp.ac.in/commdir3/list.php?division=3&deptcode=ME", 
        "http://www.iitkgp.ac.in/commdir3/list.php?division=3&deptcode=CE"]
i = 0

while i < len(urls):
    htmlfile = urllib.urlopen(urls[i])
    htmltext = htmlfile.read()
    soup = bs(htmltext)
    tables = soup.find_all('table')

    print tables
    i+=1

关于Python代码仅适用于标题标签,不适用于表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38441378/

相关文章:

python - scapy:以符号/字符串形式获取 DNSQR/DNSRR 字段值

python - 通过重新解释原始字节从一种类型的 numpy 数组转换为另一种类型

python-2.7 - scikit-learn SGD 中 class_weight 参数的作用是什么

python - OpenERP - 将数据复制到不同表中的新记录 - 费用/采购订单

python - 分割字典的键 (12-13-14) 并找到最小的数字

python - Ubuntu OpenCV:加载视频文件时程序崩溃

python - 与 C++ 相比,为什么 Python 中的系统调用要慢得多?

python - 我的 models.py 有什么问题

python - WSO2 Python 脚本中介器

python - PySpark(Python 2.7): How to flatten values after reduce