【发布时间】:2016-12-12 23:05:51
【问题描述】:
我能够在目标 URL 上抓取一个表格,但是当我尝试遍历其余页面时,我得到 - TypeError:字符串格式化期间并非所有参数都转换了
有 17 页,所以我将 var (n) 设置为最大值。并使用 for 循环进入连续页面。如果迭代组件被注释掉,代码就可以工作。是否可以定义循环以使代码更高效?
from urllib2 import urlopen
import requests
from bs4 import BeautifulSoup
n = 17
base_url = 'http://www.lowfloat.com/'
for i in range(1, n+1):
if (i == 1):
response = urlopen(base_url)
response = urlopen(base_url + "all/" %i)
html = response
print (html.response)
#html = requests.get(base_url)
soup = BeautifulSoup(html.content, "html.parser")
table = soup.find('table', attrs={'class': 'stocks'})
def target_row(tag):
is_row = len(tag.findAll('td')) > 5
row_name = tag.name == 'tr'
return is_row and row_name
rows = table.findAll(target_row)
rows = rows[1:]
for row in rows:
cells = row.findAll('td')
ticker = cells[0].get_text()
print "ticker " + ticker
【问题讨论】: