1. 程式人生 > >python爬蟲的xpath、bs4、re方法

python爬蟲的xpath、bs4、re方法

1.re正則表示式

# 正則表示式分析: 找開始和結束標籤,兩個標籤之間把想要的內容需要包含進來,然後依次查詢分析。

pat = r'<div class="post floated-thumb">(.*?)<p class="align-right"><span class="read-more">'

# 使用findall方法查詢符合要求的全部內容,放置到一個列表

divlist = re.findall(pat,HTML,re.S) #re.S : 是.匹配包括換行之內的所有字元

2.xpath(scrapy自帶的)

next=response.xpath("//li[@class='next']/a/@href").extract()[0]

extract(): 序列化該節點為unicode字串並返回list。

3.bs4

bsoup = BeautifulSoup(dataopen, "html.parser")
datas = bsoup.find_all("div", {"class":"reveal-work-wrap"}) #獲取所有這個標籤,再遍歷解析
for x in datas:
    print(x)
    childimg = x.find("img").get("src")
    pathpic1 = childimg.split("/")[-1]
    filepath1 = os.path.join("D:\putweb", pathpic1)
    urllib.request.urlretrieve(childimg,filepath1)