【问题标题】:Scraping different values (cookies?) under the same url在同一个 url 下抓取不同的值(cookie?)
【发布时间】:2015-11-11 23:03:44
【问题描述】:

我正在使用 scrapy 和 beautifulsoup 来抓取美国不同城市的所有酒店的列表。

当我进入一个名为“旧金山酒店”的页面时,它只包含该市 250 家酒店中的 30 家。单击“列表中的下一个 30”不会更改 url,也不会更改排序参数。 我的问题:我如何才能到达 250 家酒店的整个列表,或者选择要从哪个排名中抓取。谢谢。

到目前为止我的代码:

r = requests.get(url)
soup = BeautifulSoup(r.content,'html.parser')
headers = soup.find_all("h1",{"class":"X"})

for header in headers:
    headerText = header.text
    match=re.search('(.+ Hotels)',headerText)
    if match:
        writeHotels(soup,match.group(0))



def writeHotels(soup,location):

   #create Hotels directory
   hotelDir = 'Hotels/'
   if not os.path.exists(hotelDir):
       os.makedirs(hotelDir)


   hotels = soup.find_all("a",{"class":"Y"})
   name=location+'.txt'
   #write hotels to file
   if os.path.exists(hotelDir+name):
       print 'opening file '+name+"\n"
   else:
       print 'creating file '+name+"\n"
   file=open(hotelDir+name,'a') 
   for hotel in hotels:
       file.write(hotel.text+"\n")
   file.close()

【问题讨论】:

  • 可以发网址吗?
  • 这完全取决于页面本身,您需要使用 chrome develepor 工具或 firebug 之类的工具来检查正在执行的请求。

标签: python web-scraping beautifulsoup web-crawler scrapy


【解决方案1】:

如果您在页面底部的页码处查看页面源代码,则它们对每个页面都有一个唯一的 url。如果您打印出汤,您会看到您可以获取该网址。如果有很多页面,它不会显示所有页面,只是一个 ... 用于中间页面。但是,您可以根据第一个值和最后一个值计算 url(我在下面没有这样做)。这是我使用的代码:

url = "http://www.tripadvisor.com/Hotels-g60713-San_Francisco_California-Hotels.html" 
page=urllib.request.urlopen(url)

soup = BeautifulSoup(page.read())
#print(soup)
for myValue3 in soup.findAll("a",attrs={ "class" : "pageNum" }):
    try:
        print("the value of page " + myValue3.get("data-page-number") + " is: " + myValue3.get("href").split("#ACCOM_OVERVIEW")[0])
    except:
        print("error")

这是输出

the value of page 2 is: /Hotels-g60713-oa30-San_Francisco_California-Hotels.html
the value of page 3 is: /Hotels-g60713-oa60-San_Francisco_California-Hotels.html
the value of page 4 is: /Hotels-g60713-oa90-San_Francisco_California-Hotels.html
the value of page 5 is: /Hotels-g60713-oa120-San_Francisco_California-Hotels.html
the value of page 6 is: /Hotels-g60713-oa150-San_Francisco_California-Hotels.html
the value of page 8 is: /Hotels-g60713-oa210-San_Francisco_California-Hotels.html

注意网址中的-oa###-。可以更改,您可以获得所有后续页面。

【讨论】:

  • 如果页面有唯一的 url,我可以期望爬虫最终自己到达它们吗?是否有特定的爬虫规则可以让蜘蛛到达这些页面?
  • 对不起,这是一个草率的问题,我没有使用过那个工具。对于漂亮的汤,我会做一个page.read() 并打开您提取网址的每个页面。
猜你喜欢
  • 2021-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 2020-10-26
  • 2021-08-01
相关资源
最近更新 更多