Here is the Website I am trying to scrape http://livingwage.mit.edu/
特定的URL来自
http://livingwage.mit.edu/states/01
http://livingwage.mit.edu/states/02
http://livingwage.mit.edu/states/04 (For some reason they skipped 03)
...all the way to...
http://livingwage.mit.edu/states/56
在每个URL上,我需要第二个表的最后一行:
Example for http://livingwage.mit.edu/states/01
Required annual income before taxes $20,260 $42,786 $51,642 $64,767 $34,325 $42,305 $47,345 $53,206 $34,325 $47,691 $56,934 $66,997
期望输出:
阿拉巴马州20260美元42786美元51642美元64767美元34325美元42305美元47345美元53206美元34325美元47691美元56934美元66997美元
阿拉斯加24070美元49295美元60933美元79871美元38561美元47136美元52233美元61531美元38561美元54433美元66316美元82403美元
。。。在
。。。在
怀俄明州20867美元42689美元52007美元65892美元34988美元41887美元46983美元53549美元34988美元47826美元57391美元68424美元
经过2个小时的磨蹭之后,我现在所掌握的是(我是初学者):
^{pr2}$当我在Python控制台中查看状态名称和行时,它给了我html元素
[<h1>Living Wag...Alabama</h1>]
以及
[<tr class = "odd... </td> </tr>]
问题1:这些都是我想要的输出,但是我怎样才能让python以字符串格式而不是像上面那样的HTML格式给我呢?在
问题2:如何循环请求.get(url01到url56)?在
谢谢你的帮助。在
如果您能提供一种更有效的方法来获取代码中的rows变量,我将非常感激,因为我获得该变量的方法不是很像python。在
您可以通过简单地在以下行中执行操作来获取文本:
同样的方法也适用于每一行。在
相同的代码块可以放在从1到56的循环中,如下所示:
^{pr2}$zfill
将添加这些前导零。另外,如果requests.get
包含在一个try-except
块中,这样即使url错误,循环也会继续正常进行。在只需从初始页面获取所有状态,然后您就可以选择第二个表并使用css classesodd results来获得所需的tr,因为类名是唯一的,因此不需要切片:
如果运行代码,您将看到如下输出:
^{pr2}$您可以在1-53的范围内循环,但是从基本页提取锚定也可以在一个步骤中为我们提供状态名,使用该页面中的h1还可以得到阿拉巴马州的生活工资计算结果,然后你必须尝试解析,以获得名称,考虑到一些州有更多的单字名称,这不是一件小事。在
相关问题 更多 >
编程相关推荐