我正在遍历契约(Contract)的 .csv,试图从网站中提取单个列。
我想从网页末尾的表格中获取标有“商品描述”的列。但是,我无法弄清楚如何抓取列 - 只是行。
这是我目前正在使用的代码
def scraper(first, second, third):
url = "https://www.austintexas.gov/financeonline/contract_catalog/OCCViewMA.cfm?cd=%s&dd=%d&id=%s" % (first, second, third)
soup = BeautifulSoup(urllib2.urlopen(url).read())
foundtext = soup.find('td',text="Commodity Description")
table = foundtext.findPrevious('table')
rows = table.findAll('tr')
second_column = []
for row in rows:
print row.contents
我希望最终输出返回是该列中所有行的文本,行之间有回车符。
有什么想法吗?
请您参考如下方法:
对于找到的每一行,找到所有 td 元素并通过索引获取所需的元素:
table = soup.find('td', text="Commodity Description").find_parent("table")
for row in table.select("tr")[2:]: # skipping the header rows
cell = row.find_all("td")[1]
print(cell.get_text())
print("----")
打印:
WATERLINE REPLACEMENTCONSTRUCTION, PIPELINEPER YUEJIAO LIU, ADD THE REMAINING FUNDS BACK INTO THIS FUNDING LINE // PEMBERTON HEIGHTS PHASE III PROJECT ++ ENC. $53,209.97
----
WATERLINE REPLACEMENTCONSTRUCTION, PIPELINEPEMBERTON HEIGHTS PHASE III PROJECT
----
WATERLINE REPLACEMENTCONSTRUCTION, PIPELINEPEMBERTON HEIGHTS PHASE III PROJECT
----
