2017-09-24 34 views
0

在表格中,我正在刮,第二行非常長,我想簡單地限制字符因爲我只想要字符串開頭的信息。我想刮掉其他行。所以我的代碼如下:我如何限制for循環中的一個特定錶行中的字符(Python/BeautifulSoup)

table = soup.find(id="table3") 
    table_rows = table.findAll('tr') 

    for tr in table_rows: 
     td = tr.findAll('td') 
     row = [i.text.strip() for i in td] 
     print(row) 

我怎樣才能只針對第二行?

輸出具體是這樣的:

["Computer price for Apple Inc. ,\n\n\nType\nForward\n\n\n\n\n\n\nBack\n\n\n\n\nDie\n\r\n... 

所以我只想虎視眈眈的Computer price for Apple Inc. 一部分,也許有比只用字符的限制作爲一種啓發式的更好的方法。是否可以指定它來抓取所有內容,\n\n\n

回答

0

您可以使用split功能分隔文本行。我用",\n\n\n"作爲分隔符:

>>> row = 'Computer price for Apple Inc. ,\n\n\nType\nForward\n\n\n\n\n\n\nBack\n\n\n\n\nDie\n\r\n' 
>>> row.split(sep=",\n\n\n", maxsplit=1)[0] 
'Computer price for Apple Inc. ,' 
+0

謝謝!但是如何在多個頁面拼出時將其寫出來,每個頁面對於不同的公司都有不同的計算機價格。 – Jason

+0

好吧,沒關係,想通了,謝謝! – Jason