嗨,伙计们定义了一个函数,从python的txt文件中的链接中获取底部所有分页的url的列表。在
这是我需要做的一个例子。在
输入链接
http://www.apartmentguide.com/apartments/Alabama/Hartselle/
期望输出
^{pr2}$以限制每个输入Url的限制。在
这是我目前为止编写的函数,但它不起作用我也不擅长Python。在
import requests
#from bs4 import BeautifulSoup
from scrapy import Selector as Se
import urllib2
lists = open("C:\Users\Administrator\Desktop\\3.txt","r")
read_list = lists.read()
line = read_list.split("\n")
def get_links(line):
for each in line:
r = requests.get(each)
sel = Se(text=r.text, type="html")
next_ = sel.xpath('//a[@class="next sprite"]//@href').extract()
for next_1 in next_:
next_2 = "http://www.apartmentguide.com"+next_1
print next_2
get_links(next_1)
get_links(line)
下面是两种方法。在
一种使用
mechanize
使用url会更聪明一些,但速度要慢得多,而且可能会过度依赖于你正在做的其他事情。在另一个使用}则从你列出的页面中的相对url中形成绝对url。在
requests
来获取页面(urllib2就足够了),BeautifulSoup
来解析标记,而{请注意,这两个函数都返回以下列表:
^{pr2}$有重复的。你可以通过改变
到
不管你选择什么方法。在
编辑:
我注意到上面的函数只返回到第2-5页的链接,而您必须浏览这些页面才能看到实际上有10个页面。在
一种完全不同的方法是从“根”页面中获取结果的数量,然后预测将产生多少个页面,然后从中构建链接。在
由于每页有20个结果,计算出多少页是很简单的,考虑一下:
这将是3种方法中最快的,但可能更容易出错。在
编辑2:
可能是这样的:
对于Re我不确定,所以尝试了xpath。在
相关问题 更多 >
编程相关推荐