Seleniumを使用してWebサイトをスクレイピングしています。要素(ヘッダー)のリストのテキストを取得すると、次のように出力されます。
['Countyarrow_upward Reportingarrow_upward Totalarrow_upward Bennet (D)arrow_upward Biden (D)arrow_upward Bloomberg (D)arrow_upward Booker (D)arrow_upward Boyd (D)arrow_upward Buttigieg (D)arrow_upward
Castro (D)arrow_upward De La Fuente III (D)arrow_upward Delaney (D)arrow_upward Ellinger (D)arrow_upward Gabbard (D)arrow_upward Greenstein (D)arrow_upward Klobuchar (D)arrow_upward Patrick (D)arrow_upw
ard Sanders (D)arrow_upward Sestak (D)arrow_upward Steyer (D)arrow_upward Warren (D)arrow_upward Williamson (D)arrow_upward Yang (D)arrow_upward']
明らかに名前と「(D)」だけが必要なので、replace()関数を使用してCountyarrow_upward Reportingarrow_upward Totalarrow_upward
とarrow_upward
を空の文字列に置き換えてみました。これが私のコードです:
headers = driver.find_elements_by_xpath('//*[@id="content"]/div/div[3]/div/div[2]/div/div[2]/div/div[2]/div[1]/div/table/thead/tr[1]')
header_text = []
for i in headers:
header_raw_text = i.text
header_raw_text.replace("Countyarrow_upward Reportingarrow_upward Totalarrow_upward ", "")
header_raw_text.replace("arrow_upward ", "")
header_text.append(header_raw_text)
print(header_text)
このコードを実行すると、上記と同じ結果が得られ、replace()関数が機能しません。
ヘルプは大歓迎です!
文字列は不変です。したがってheader_raw_text.replace()
、文字列自体は変更されません。置換後に結果を再割り当てする必要があります。
header_raw_text = header_raw_text.replace("arrow_upward ", "")
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加