import requests
from bs4 import BeautifulSoup
import pandas as pd
header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
def scrap_hrefs(url,baseUrl):
resp = requests.get(url, headers= header)
respData = BeautifulSoup(resp.content, 'html.parser')
allHrefs = respData.select('[href]')
return allHrefs, baseUrl
def get_hrefs(allHrefs, baseUrl):
for i in range(0,len(allHrefs)):
if allHrefs[i]['href'].startswith('/'):
allHrefs[i]= baseUrl + allHrefs[i]['href']
else:
allHrefs[i]= allHrefs[i]['href']
return allHrefs
def store_hrefs(allHrefs):
links = {'links' : allHrefs}
df = pd.DataFrame(links).drop_duplicates()
for i in range(len(df.index)):
if df['links'].str.contains('https')==False:
df.drop()
df.to_csv("example_home_page_links.csv", index=False)
return df
def run_scraper(url,baseUrl) :
store_hrefs(get_hrefs(*scrap_hrefs(url, baseUrl)))
run_scraper('https://www.example.com/','https://www.example.com')
此代码出现以下错误:
ValueError:序列的真值不明确。使用a.empty、a.bool()、a.item()、a.any()或a.all()。
我想删除其中没有“https”的所有行(即删除所有无效链接/内容)
您可以在循环中更改remove
False
输出:要仅筛选^{} 中具有匹配条件的行,请执行以下操作:
相关问题 更多 >
编程相关推荐