|
| 1 | +from bs4 import BeautifulSoup |
| 2 | +import csv |
| 3 | +import pprint |
| 4 | +import re |
| 5 | +import requests |
| 6 | +import time |
| 7 | + |
| 8 | + |
| 9 | +def get_book_data(element): |
| 10 | + """given a BeautifulSoup Tag representing a book, |
| 11 | + extract the book's details and return a dict""" |
| 12 | + |
| 13 | + title = element.find('div', 'thumbheader').a.text |
| 14 | + by_author = element.find('div', 'AuthorName').text |
| 15 | + authors = [x.strip() |
| 16 | + for x in re.sub("by ", '', by_author, flags=re.IGNORECASE).split(',') |
| 17 | + ] |
| 18 | + # price = element.find('span', 'price').text.strip() |
| 19 | + |
| 20 | + return { |
| 21 | + 'title': title, |
| 22 | + # 'price': price, |
| 23 | + 'authors': authors, |
| 24 | + } |
| 25 | + |
| 26 | + |
| 27 | +def main(): |
| 28 | + NUM_PAGES = 31 |
| 29 | + books = [] |
| 30 | + |
| 31 | + base_url = 'http://shop.oreilly.com/category/browse-subjects/data.do?sortby=publicationDate&page=' |
| 32 | + |
| 33 | + for page_num in range(1, NUM_PAGES + 1): |
| 34 | + print("souping page", page_num, ",", len(books), " found so far") |
| 35 | + html = requests.get(base_url + str(page_num)).text |
| 36 | + soup = BeautifulSoup(html, 'html5lib') |
| 37 | + books.extend([get_book_data(group) for group in soup('td', 'thumbtext')]) |
| 38 | + |
| 39 | + time.sleep(30) |
| 40 | + |
| 41 | + with open('books.txt', 'w') as file: |
| 42 | + writer = csv.writer(file, delimiter=',') |
| 43 | + writer.writerow(["Title", "Authors"]) |
| 44 | + for book in books: |
| 45 | + writer.writerow([book['title'], ', '.join(book['authors'])]) |
| 46 | + |
| 47 | + pprint.pprint(books) |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + main() |
0 commit comments