鍍金池/ 問答/Python/ python里面使用BS4爬取的頁面代碼里面有部分XML數(shù)據(jù)如何提取

python里面使用BS4爬取的頁面代碼里面有部分XML數(shù)據(jù)如何提取

python爬過過來的html數(shù)據(jù)里面有一段數(shù)據(jù),我想取里面的鏈接地址和標題,以及發(fā)布的日期,但是使用find_all()獲取不到里面的數(shù)據(jù),應該如何獲取?
爬過來的數(shù)據(jù)格式如下:


<record><![CDATA[
<tr><td height="26" align="left" style="border-bottom:dashed 1px #ccc"><span style="padding-right:8px;"><img src="/picture/0/s1609271437127167930.gif" align="absmiddle" border="0"></span><a  style="font-size:12px;" href='/art/2018/1/2/art_275_32953.html' class='bt_link' title='考核合格名單的通知' target="_blank">2017年度學科帶頭人考核合格名單的通知</a></td><td width="80" align="center" class="bt_time" style="border-bottom:dashed 1px #ccc">[2018-01-02]</td></tr>]]></record>
回答
編輯回答
嘟尛嘴

根據(jù)您提出胡思路,有了自己的解決方案。
先用BS獲取到目標網頁數(shù)據(jù)段信息,再用正則表達取得里面的數(shù)據(jù)。


from bs4 import BeautifulSoup


# 定義一個通知新聞的類型
class News(object):
    def __init__(self):
        self.__url = None
        self.__title = None
        self.__posttime = None

    def print_info(self):
        print('%s: %s:%s' % (self.__title, self.__posttime, self.__url))

    def set_url(self, url):
        self.__url = url

    def set_title(self, title):
        self.__title = title

    def set_posttime(self, posttime):
        self.__posttime = posttime

    def get_url(self):
        return self.__url

    def get_title(self):
        return self.__title

    def get_posttime(self):
        return self.__posttime



newslist = []
# 保存最新的通知列表
for link in soup.find_all(attrs={'id': '494'}):
    # print(link)
    # 獲取兩個td里面的內容
    tr=re.findall(r'<tr[^>]*>(.*?)</tr>',str(link),re.I|re.M)
    #print(tr)
    for trs in tr:
        notice = News()
        #print(trs)
        td = re.findall(r'<td[^>]*>(.*?)</td>', str(trs), re.I | re.M)
        # print(td)
        i = 1
        for newid in td:
            # 第一個TD里面的內容存放的是網址和標題
            # print(newid)
            # 第二個TD里面的內容存放的是發(fā)布日期
            if (i % 2) == 0:
                posttime = newid
                notice.set_posttime(posttime)
                i = i + 1
                #notice.print_info()
                newslist.append(notice)
            else:
                # 進一步分解第一個TD里面的內容,分別獲取鏈接和標題屬性
                url = re.findall(r'href=\'(\S+)\'', str(newid))
                finalurl = "http://www.zjedu.org" + str(url[0])
                # print(finalurl)
                title = re.findall(r'title=\'(.*?)\'', str(newid))
                stitle=str(title[0]).strip()
                notice.set_url(finalurl)
                print(stitle)
                notice.set_title(stitle)
                i = i + 1
                      
                
                

輸出的結果如下:
2017年度學科帶頭人考核合格名單的通知: [2018-01-02]:/art/2018/1/2/art_275_33408.html
2017年9月2日 04:29
編輯回答
挽青絲
from bs4 import BeautifulSoup

a = """<record><![CDATA[ \
<tr><td height="26" align="left" style="border-bottom:dashed 1px #ccc"><span style="padding-right:8px;"> \
<img src="/picture/0/s1609271437127167930.gif" align="absmiddle" border="0"></span>2017年度學科帶頭人考核 \
合格名單的通知</td><td width="80" align="center" class="bt_time" style="border-bottom:dashed 1px #ccc">[20 \
18-01-02]</td></tr>]]></record>"""

soup= BeautifulSoup(a, 'lxml')
img = soup.img.get('src')
print(img)
td = soup.find_all('td')
for x in td:
    print(x.string)

結果:

/picture/0/s1609271437127167930.gif
None
[20 18-01-02]

我用beautifulsoup無法得到 2017年度學科帶頭人考核 合格名單的通知 這個title,原因是使用string的時候,標簽內最多有一個子標簽才可以,而td下有span和img兩個子標簽,所以顯示none了。固配合了正則表達式來解決,如下:

from bs4 import BeautifulSoup
import re

a = """<record><![CDATA[ \
<tr><td height="26" align="left" style="border-bottom:dashed 1px #ccc"><span style="padding-right:8px;"> \
<img src="/picture/0/s1609271437127167930.gif" align="absmiddle" border="0"></span>2017年度學科帶頭人考核 \
合格名單的通知</td><td width="80" align="center" class="bt_time" style="border-bottom:dashed 1px #ccc">[20 \
18-01-02]</td></tr>]]></record>"""

soup= BeautifulSoup(a, 'lxml')
img = soup.img.get('src')
td = soup.find_all('td')
pattern = re.compile(r'<td.+?><span.+?>.+?</span>(.+?)</td>')
title = ''.join(re.findall(pattern, str(td[0]))[0])

print(img)
print(title)
print(td[1].string)

運行結果:

/picture/0/s1609271437127167930.gif
2017年度學科帶頭人考核 合格名單的通知
[20 18-01-02]
2017年10月18日 07:12