[英]Get line which contains string
我正在嘗試從包含某些字符序列的文本文件中獲取一行:
我的輸入:
<tr><td>lucas.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> </tr>
<tr><td>jeanpierre.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span title="Cannot connect to 193.191.187.25:22345." style="color:red;font-weight:bold">X</span></td> <td><span title="No response from DNS at 193.191.187.25." style="color:red;font-weight:bold">X</span></td> </tr>
<tr><td>sofie.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span title="Cannot connect to 193.191.187.26:22345." style="color:red;font-weight:bold">X</span></td> <td><span title="No response from DNS at 193.191.187.26." style="color:red;font-weight:bold">X</span></td> </tr>
<tr><td>thomas.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> </tr>
現在,我需要獲取包含lucas的行,我使用了beautifulsoup嘗試了此操作,但這並不意味着僅獲取html標簽內容,所以我嘗試了使用常規in運算符:
def soupParserToTable(self,input):
global header
soup = self.BeautifulSoup(input)
header = soup.first('tr')
tableInput='0'
for line in input:
if 'lucas' in line:
tableInput = line
print tableInput
但是它一直返回0而不是
<tr><td>lucas.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> </tr>
如果input
只是一個字符串,則for line in input
中的行不會迭代行,而是迭代字符。 因此,永遠不會在一個字符的字符串中找到'lucas'
並且不會分配tableInput
。 僅當對象是文件時,才會發生基於行的迭代行為。
如果要遍歷字符串的每一行,則必須執行以下操作:
for line in input.split('\n'):
...
既然您有BeautifulSoup可用,我會說,用它來讀取每一行的第一個單元格的值要好得多,而不是依賴粗略而脆弱的字符串搜索。
預計到達時間:
我如何獲取包含字符串'lucas'的行的表條目的任何提示?
使用td.parent
獲取包含行, td.parent.parent
獲取包含表/ tbody,依此類推。
如果要在下一列中獲得V
或X
,則可以這樣說:
tr= soup.find(text= re.compile('lucas')).parent.parent
vorx= tr.findAll('td')[1].find('span').string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.