【问题标题】:Append scraped data to different columns将抓取的数据附加到不同的列
【发布时间】:2015-09-26 18:09:46
【问题描述】:
while True:
        for rate in soup.find_all('div',{"class":"rating"}):
         if rate.img is not None:   
               print (rate.img['alt'])
        try:
            driver.find_element_by_link_text('Next').click()
        except:
            break

driver.quit()


while True:
         for rate in soup.findAll('div',{"class":"listing_title"}):
            print (rate.a.text)
         try:
             driver.find_element_by_link_text('Next').click()
         except:
             break

driver.quit()

【问题讨论】:

  • 爬取网站是违反TripAdvisor的terms of service的。请不要这样做。

标签: python selenium web-scraping beautifulsoup


【解决方案1】:

这应该可以满足您的需求。您应该获取两者的父类(我选择了.listing,并从那里获取每个属性,将它们插入到字典中,然后使用 Python CSV 库将字典写入 CSV。作为一个公平的警告,我没有直到它坏了才运行它,我只是在第二个循环之后就坏了以节省一些计算。

警告尚未在完整站点上测试

import csv
import time

from bs4 import BeautifulSoup
import requests
from selenium import webdriver

url = 'http://www.tripadvisor.in/Hotels-g186338-London_England-Hotels.html'

driver = webdriver.Firefox()
driver.get(url)

hotels = []

while True:
    html = driver.page_source
    soup = BeautifulSoup(html)
    listings = soup.select('div.listing')

    for l in listings:
        hotel = {}
        hotel['name'] =  l.select('a.property_title')[0].text
        hotel['rating'] = float(l.select('img.sprite-ratings')[0]['alt'].split('of')[0])
        hotels.append(hotel)

    next = driver.find_element_by_link_text('Next')
    if not next:
        break
    else:
        next.click()
        time.sleep(0.5)

if len(hotels) > 0:
    with open('ratings.csv', 'w') as f:
        fieldnames = [ k for k in hotels[0].keys() ]
        writer = csv.DictWriter(f,fieldnames=fieldnames)
        writer.writeheader()
        for h in hotels:
            writer.writerow(h)

driver.quit()

【讨论】:

  • 请不要破坏你的答案。
【解决方案2】:

您应该考虑使用list。

我会尝试这样的:

for rate in soup.findAll('div',{"class":["rating","listing_title"]}):

(可能是错的,这台机器没有bs4供我检查,抱歉)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 2021-11-29
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多