2017-01-02 60 views
0

我使用python 3.6和Pycharm 2016.2擔任主編爬行對標籤從HTML

我想爬「號」內的對內容:「TD」標籤,如果「TD」標籤都有一個子標籤是「checked ='chedcked'」的輸入標籤。我試過regEx,來自BeautifulSoup和其他人的find_all,但仍然有錯誤消息。

請幫忙。

這是網站地址:http://www.bobaedream.co.kr/mycar/popup/mycarChart_4.php?zone=C&cno=652691&tbl=cyber

下面是我的代碼:

from bs4 import BeautifulSoup 
import urllib.request 
from urllib.parse import urlparse 
import re 

popup_inspection = "http://www.bobaedream.co.kr/mycar/popup/mycarChart_4.php?zone=C&cno=652691&tbl=cyber" 
res = urllib.request.urlopen(popup_inspection) 
html = res.read() 
soup_inspection = BeautifulSoup(html, 'html.parser') 

insp_trs = soup_inspection.find_all('tr') 
for insp_tr in insp_trs: 
    # print(insp_td.text) 
    th = insp_tr.find('th') 
    td = insp_tr.find('td') 

    if td.find('input', checked=''): 
     print(th, ":", td) 
    else: pass 
+0

請顯示錯誤信息。如果我們不知道錯誤是什麼,我們無法幫助您解決問題。 – DyZ

回答

1

的想法是使用一個searching function定位th元素後跟一個td兄弟。然後,我們可以使用type="radio"checked屬性找到input元素。如果有的話,我們可以在收音機input之後找到label元素。

樣品實施:

import requests 
from bs4 import BeautifulSoup 


url = "http://www.bobaedream.co.kr/mycar/popup/mycarChart_4.php?zone=C&cno=652691&tbl=cyber" 
with requests.Session() as session: 
    session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36'} 

    page = session.get(url) 
    soup = BeautifulSoup(page.content, "html.parser") 

    for label in soup.find_all(lambda tag: tag.name == "th" and tag.find_next_sibling('td')): 
     value_cell = label.find_next_sibling('td') 

     # if combobox cell 
     selected_value = value_cell.find("input", type="radio", checked=True) 
     if selected_value: 
      value = selected_value.find_next("label").get_text() 
      print(label.get_text(), value) 

目前打印:

10. 보증유형 자가보증 
13. 사고/침수유무(단순수리제외) 무 
12. 불법구조변경 없음 

這當然可以而且應該進一步提高,但是我希望在片斷中所使用的技術將幫助你去最終的解決方案。

+0

我深深地感謝您的評論。我試着用你的代碼,但它不斷返回第一個表中的內容,不包括其餘的表。我檢查了其他具有類似標籤佈局的表格,例如(「input」,type =「radio」,checked = True),但結果不能返回它們。你知道爲什麼它發生了嗎? –

+0

我甚至在代碼的開頭添加了這段代碼(對於soup_inspection.find_all中的insp_table('table',class_ = True):) –

+0

@신종원看起來像'checked = True'不適用於其他情況 - 輸入元素沒有'checked'屬性..謝謝。 – alecxe