一、使用bs4库爬取丁香园:http://www.dxy.cn/bbs/thread/626626#626626
的回复内容,话不多说,直接上代码:
import requests
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
def get_one_page(url):
try:
headers = {
‘User-Agent’: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36’
}
r= requests.get(url, headers=headers)
if r.status_code == 200:
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
return None
except RequestException:
return None
def parse_one_page(html):
soup=BeautifulSoup(html,“html.parser”)
name=soup.find_all(name=“div”,attrs={“class”:“auth”})
floor=soup.find_all(name=“span”,attrs={“class”:“layer”})
comment=soup.find_all(name=“td”,attrs={“class”:“postbody”})
content=[name,floor,comment]
return content
def write_to_file(content):
f=open(‘结果.text’,‘a’,encoding=‘utf-8’)
for i in range(4):
f.write(" “.join([str(content[0][i].get_text()),str(content[1][i].get_text())]))
f.write(str(content[2][i].get_text())+”\n")
f.close()
def main():
url = “http://www.dxy.cn/bbs/thread/626626#626626”
html = get_one_page(url)
content=parse_one_page(html)
write_to_file(content)
print(“爬取成功!”)
main()
爬取结果:
我始终没弄明白为什么只能爬取前四个回复,明明结构几乎完全一样,时间匆急,留待后日细细思索。
二、使用Xpath库
直接上代码:
爬取结果:
此次爬取不完善,后续有时间会改进!