我能够在目标网址上抓一张桌子,但是当我尝试迭代其余页面时,我得到了 - 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
答案 0 :(得分:1)
您不需要使用%来传递变量:
response = urlopen(base_url + "all/" %i)
应该是:
response = urlopen(base_url + "all/" + str(i))
另外,我不明白为什么要在第一次使用这个...