import requests
import re
import json
import time
from bs4 import BeautifulSoup
from pyquery import PyQuery as pq
from lxml import etree
def get_one_page(url):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
except requests.exceptions.RequestException as r:
return None
def parse_one_page(html):
pattern = re.compile(
'<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
items = re.findall(pattern, html)
for item in items:
yield{
'index': item[0],
'image': item[1],
'title': item[2].strip(),
'actor': item[3].strip()[3:],
'time': item[4].strip()[5:],
'score': item[5].strip()+item[6].strip()
}
def xpath_demo(html):
html=etree.HTML(html)
str1='//dd['
for i in range(10):
yield{
'index': html.xpath(str1+str(i)+']/i/text()'),
'image': html.xpath(str1+str(i)+']/a/img[@class="board-img"]/@data-src'),
'title': html.xpath(str1+str(i)+']//p/a[@data-act="boarditem-click"]/text()'),
'actor': ''.join(html.xpath(str1+str(i)+']//p[@class="star"]/text()')).strip(),
'time': html.xpath(str1+str(i)+']//p[@class="releasetime"]/text()'),
'score': ''.join(html.xpath(str1+str(i)+']//p[@class="score"]/i/text()')),
}
def bs4_demo(html):
soup = BeautifulSoup(html, 'lxml')
for dd in soup.find_all(name='dd'):
yield{
'index': dd.find(name='i', attrs={'class': 'board-index'}).string.strip(),
'image': dd.find(name='img', attrs={'class': 'board-img'})['data-src'],
'title': dd.find(name='p', attrs={'class': 'name'}).string.strip(),
'actor': dd.find(name='p', attrs={'class': 'star'}).string.strip(),
'time': dd.find(name='p', attrs={'class': 'releasetime'}).string.strip(),
'score': dd.find(name='i', attrs={'class': 'integer'}).string+dd.find(name='i', attrs={'class': 'fraction'}).string
}
def pyquery_demo(html):
doc=pq(html)
for dd in doc('dd').items():
yield{
'index': dd.find('i.board-index').text(),
'image': dd.find('img.board-img').attr('data-src'),
'title': dd.find('p.name a').text(),
'actor': dd.find('p.star').text(),
'time': dd.find('p.releasetime').text(),
'score': dd.find('p.score i.integer').text()+dd.find('p.score i.fraction').text()
}
def write_to_file(content):
with open('/Users/zz/Desktop/result.txt', 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False)+'/n')
def main(offset):
url = 'https://maoyan.com/board/4?offset='+str(offset)
html = get_one_page(url)
for item in xpath_demo(html):
print(item)
if __name__ == '__main__':
for i in range(10):
main(offset=i*10)
time.sleep(1)
複製代碼