2017-01-02 58 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