【问题标题】:Iterating through URLs with python to scrape similar tables使用 python 遍历 URL 以抓取类似的表
【发布时间】: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

【问题讨论】:

    标签: python url iteration bs4


    【解决方案1】:

    你不需要使用 % 来传递变量:

    response = urlopen(base_url + "all/" %i)
    

    应该是:

    response = urlopen(base_url + "all/" + str(i))
    

    我也不明白为什么在第一个中使用这个...

    【讨论】:

    • 这是错误切换 % 到 + - TypeError: cannot concatenate 'str' and 'int' objects
    • ...'if' 是从第一页抓取数据。
    猜你喜欢
    • 2023-03-28
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 2020-08-28
    • 2014-04-22
    • 2020-09-20
    相关资源
    最近更新 更多