from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import csv
url = 'http://music.163.com/#/discover/playlist/?order=hot&cat=%E5%85%A8%E9%83%A8&limit=35&offset=0'
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.binary_location = r'/Applications/Google Chrome.app'
driver = webdriver.Chrome()
csv_file = open("playlist.csv", "w", newline='')
writer = csv.writer(csv_file)
writer.writerow(['Title', 'Number broadcast', 'Link'])
while url != 'javascript:void(0)':
driver.get(url)
driver.switch_to.frame("contentFrame")
# locate the song list tag
data = driver.find_element_by_id("m-pl-container").find_elements_by_tag_name("li")
# analyze all song lists in a page
for i in range(len(data)):
nb = data[i].find_element_by_class_name("nb").text
if '万' in nb and int(nb.split('万')[0]) > 500:
msk = data[i].find_element_by_css_selector("a.msk")
writer.writerow([msk.get_attribute('title'), nb, msk.get_attribute('href')])
url = driver.find_element_by_css_selector("a.zbtn.znxt").get_attribute('href')
csv_file.close()
Debug log:
- 无头浏览器PhantomJS版本过旧,需要装载Chrome Headless。
i. 首先使用Homebrew下载chromedriver。
ii. 在.py文档中加入如下代码:from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') chrome_options.binary_location = r'/Applications/Google Chrome.app' driver = webdriver.Chrome()
- Traceback (most recent call last):
File "/Users/wuhaoyang/PycharmProjects/crawler/crawler.py", line 26, in <module>
for i in range(len(data)):
TypeError: object of type 'WebElement' has no len()
将文档里find_elements_by_tag_name("li") 更改为 find_elements_by_tag_name("li")
- 使用Windows的同学遇到了一个编码上的问题,下面是Stackoverflow的回答。但她并没有成功修改编码方式,已向拓海up私信请教,如有回复再更新。
UnicodeEncodeError: 'gbk' codec can't encode character '\ufe0f' in position 10: illegal multibyte sequenceUnicode
(1) encode with 'gbk' but use the 'replace' option
(2) encode with 'gbk' but use the 'ignore' option
(3) encode with an encoding that supports ALL Unicode characters (utf-8, gb18030) and for which you have a display mechanism that renders all those characters that aren't in gbk