나는 beautifulsoup
을 사용하여 URL 페이지에서 href 링크를 추출한 다음 url 이름과 추출 된 링크를 추가하여 목록에 목록을 만듭니다.두 개의 다른 요소를 목록에 추가하는 방법
[['www.example.com', 'www.example.com/extractedlink1', 'www.example.com/extractedlink2'],['www.apple.com', 'www.apple.com/exractedlink1']...]
나는 문제가 두 가지 요소가 추가되어 데 부분을 예를 들어, 각 URL에 대한, 내가 만드는 페이지에 액세스하고 링크에서 URL을 추출 한 다음 목록에서 목록에 추가 할 목록에있는 목록에. 다음, url_list
는 URL을 추출 전을 위해 액세스 할 수와 목록) ['www.example.com', 'www.apple.com'....]
url_and_extracted = []
for i in range(0,len(url_list)):
url = url_list[i]
driver = webdriver.PhantomJS()
driver.get(url)
time.sleep(2)
html = driver.page_source
driver.close()
soup = BeautifulSoup(html, "html.parser")
for div in soup.find_all("div", attrs={"class" : "article-content entry-content"}):
url_and_extracted.append([url_list[i],str(div.find("a")['href'])])
는하지만 마지막 부분이있다 같은 원래 URL과 함께 여러 목록을 초래할 것, 옳다고 생각하지 않는다 하나의 URL에서 하나 이상의 링크가 추출되었습니다. 내가 원했던 것은 원본 url과 추출 된 Hrefs가있는 목록 내의 하나의 목록입니다.
{'www.example.com': ['www.example.com/extractedlink1', 'www.example.com/extractedlink2']}
당신의 코드가 작동하지 않는 이유는이 부분이다 :
for div in soup.find_all("div", attrs={"class" : "article-content entry-content"}):
url_and_extracted.append([url_list[i],str(div.find("a")['href'])])
는 각 iterration i
의에서 url_and_extracted
에 추가해야
, 당신은하지 않습니다 원래'url_and_extracted'가 필요합니다. –
@BurhanKhalid 코드를 실행했지만 작동했지만 결과가 매우 이상합니다. 사전 형식이지만 "defaultdict (")가 각 사전 항목 사이에 삽입되었습니다. –
song0089
그래서 어떻게 인쇄되는지 보지 마십시오. –