从一个文本文件中读取多个URL,处理每个网页,并抓取其中的内容



我有一个.txt文件,其中包含多个URL的列表。我的目的是打开这个.txt文件,访问每行中的每个URL,刮取每个URL中的内容,并将txt文件中包含多个URL列表的内容附加到";draft.csv";文件

当我尝试运行其他代码时,推荐的请求结果显示";请打开JavaScript并刷新页面";,所以我打算用Selenium来解决这个问题。我可以根据需要获取所有页面,但无法在每个链接中看到所需的内容。

以下是多个URL的列表,例如:

http://example.com/2267/15175/index.html
http://example.com/2267/16796/index.html
http://example.com/2267/17895/index.html

这是我当前使用Selenium和Request的代码。

from lxml import etree
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import sys
import pandas as pd
import urllib.request
import requests
frame =[]
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options = chrome_options)
with open("draft.txt", "r") as file:
for line in file:
url = line.rstrip("n")
print(url)
driver.get(url)
html = etree.HTML(driver.page_source)
allurl = requests.get(url)
htmltext = allurl.text
extract_link = html.xpath('//span[@id="my_two"]/table/tbody/tr/td/table[2]')
for i in extract_link:
link = i.xpath('./tbody/tr/td/div/p/a/@href')
content = 'http://example.com'+ link[0]
frame.append({
'content': content,
})
dfs = pd.DataFrame(frame)
dfs.to_csv('draft.csv',index=False,encoding='utf-8-sig')

提前感谢你帮我做这件事!

必须在for循环中加载selenium,并且可以使用bs4进行刮擦:

from selenium import webdriver
from bs4 import BeautifulSoup
f = open("urls.txt")
urls = [url.strip() for url in f.readlines()]
For url in urls:
driver.get(url)
...
html = driver.page_source
soup = BeautifulSoup(html)
Information = soup.find('title')
Url = url
...
driver.quit()

最新更新