test_html.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  1. from collections.abc import Iterator
  2. from functools import partial
  3. from io import (
  4. BytesIO,
  5. StringIO,
  6. )
  7. import os
  8. from pathlib import Path
  9. import re
  10. import threading
  11. from urllib.error import URLError
  12. import numpy as np
  13. import pytest
  14. from pandas.compat import is_platform_windows
  15. import pandas.util._test_decorators as td
  16. import pandas as pd
  17. from pandas import (
  18. NA,
  19. DataFrame,
  20. MultiIndex,
  21. Series,
  22. Timestamp,
  23. date_range,
  24. read_csv,
  25. read_html,
  26. to_datetime,
  27. )
  28. import pandas._testing as tm
  29. from pandas.io.common import file_path_to_url
  30. @pytest.fixture(
  31. params=[
  32. "chinese_utf-16.html",
  33. "chinese_utf-32.html",
  34. "chinese_utf-8.html",
  35. "letz_latin1.html",
  36. ]
  37. )
  38. def html_encoding_file(request, datapath):
  39. """Parametrized fixture for HTML encoding test filenames."""
  40. return datapath("io", "data", "html_encoding", request.param)
  41. def assert_framelist_equal(list1, list2, *args, **kwargs):
  42. assert len(list1) == len(list2), (
  43. "lists are not of equal size "
  44. f"len(list1) == {len(list1)}, "
  45. f"len(list2) == {len(list2)}"
  46. )
  47. msg = "not all list elements are DataFrames"
  48. both_frames = all(
  49. map(
  50. lambda x, y: isinstance(x, DataFrame) and isinstance(y, DataFrame),
  51. list1,
  52. list2,
  53. )
  54. )
  55. assert both_frames, msg
  56. for frame_i, frame_j in zip(list1, list2):
  57. tm.assert_frame_equal(frame_i, frame_j, *args, **kwargs)
  58. assert not frame_i.empty, "frames are both empty"
  59. def test_bs4_version_fails(monkeypatch, datapath):
  60. bs4 = pytest.importorskip("bs4")
  61. pytest.importorskip("html5lib")
  62. monkeypatch.setattr(bs4, "__version__", "4.2")
  63. with pytest.raises(ImportError, match="Pandas requires version"):
  64. read_html(datapath("io", "data", "html", "spam.html"), flavor="bs4")
  65. def test_invalid_flavor():
  66. url = "google.com"
  67. flavor = "invalid flavor"
  68. msg = r"\{" + flavor + r"\} is not a valid set of flavors"
  69. with pytest.raises(ValueError, match=msg):
  70. read_html(StringIO(url), match="google", flavor=flavor)
  71. def test_same_ordering(datapath):
  72. pytest.importorskip("bs4")
  73. pytest.importorskip("lxml")
  74. pytest.importorskip("html5lib")
  75. filename = datapath("io", "data", "html", "valid_markup.html")
  76. dfs_lxml = read_html(filename, index_col=0, flavor=["lxml"])
  77. dfs_bs4 = read_html(filename, index_col=0, flavor=["bs4"])
  78. assert_framelist_equal(dfs_lxml, dfs_bs4)
  79. @pytest.fixture(
  80. params=[
  81. pytest.param("bs4", marks=[td.skip_if_no("bs4"), td.skip_if_no("html5lib")]),
  82. pytest.param("lxml", marks=td.skip_if_no("lxml")),
  83. ],
  84. )
  85. def flavor_read_html(request):
  86. return partial(read_html, flavor=request.param)
  87. class TestReadHtml:
  88. def test_literal_html_deprecation(self, flavor_read_html):
  89. # GH 53785
  90. msg = (
  91. "Passing literal html to 'read_html' is deprecated and "
  92. "will be removed in a future version. To read from a "
  93. "literal string, wrap it in a 'StringIO' object."
  94. )
  95. with tm.assert_produces_warning(FutureWarning, match=msg):
  96. flavor_read_html(
  97. """<table>
  98. <thead>
  99. <tr>
  100. <th>A</th>
  101. <th>B</th>
  102. </tr>
  103. </thead>
  104. <tbody>
  105. <tr>
  106. <td>1</td>
  107. <td>2</td>
  108. </tr>
  109. </tbody>
  110. <tbody>
  111. <tr>
  112. <td>3</td>
  113. <td>4</td>
  114. </tr>
  115. </tbody>
  116. </table>"""
  117. )
  118. @pytest.fixture
  119. def spam_data(self, datapath):
  120. return datapath("io", "data", "html", "spam.html")
  121. @pytest.fixture
  122. def banklist_data(self, datapath):
  123. return datapath("io", "data", "html", "banklist.html")
  124. def test_to_html_compat(self, flavor_read_html):
  125. df = (
  126. DataFrame(
  127. np.random.default_rng(2).random((4, 3)),
  128. columns=pd.Index(list("abc")),
  129. )
  130. # pylint: disable-next=consider-using-f-string
  131. .map("{:.3f}".format).astype(float)
  132. )
  133. out = df.to_html()
  134. res = flavor_read_html(
  135. StringIO(out), attrs={"class": "dataframe"}, index_col=0
  136. )[0]
  137. tm.assert_frame_equal(res, df)
  138. def test_dtype_backend(self, string_storage, dtype_backend, flavor_read_html):
  139. # GH#50286
  140. df = DataFrame(
  141. {
  142. "a": Series([1, np.nan, 3], dtype="Int64"),
  143. "b": Series([1, 2, 3], dtype="Int64"),
  144. "c": Series([1.5, np.nan, 2.5], dtype="Float64"),
  145. "d": Series([1.5, 2.0, 2.5], dtype="Float64"),
  146. "e": [True, False, None],
  147. "f": [True, False, True],
  148. "g": ["a", "b", "c"],
  149. "h": ["a", "b", None],
  150. }
  151. )
  152. out = df.to_html(index=False)
  153. with pd.option_context("mode.string_storage", string_storage):
  154. result = flavor_read_html(StringIO(out), dtype_backend=dtype_backend)[0]
  155. if dtype_backend == "pyarrow":
  156. pa = pytest.importorskip("pyarrow")
  157. string_dtype = pd.ArrowDtype(pa.string())
  158. else:
  159. string_dtype = pd.StringDtype(string_storage)
  160. expected = DataFrame(
  161. {
  162. "a": Series([1, np.nan, 3], dtype="Int64"),
  163. "b": Series([1, 2, 3], dtype="Int64"),
  164. "c": Series([1.5, np.nan, 2.5], dtype="Float64"),
  165. "d": Series([1.5, 2.0, 2.5], dtype="Float64"),
  166. "e": Series([True, False, NA], dtype="boolean"),
  167. "f": Series([True, False, True], dtype="boolean"),
  168. "g": Series(["a", "b", "c"], dtype=string_dtype),
  169. "h": Series(["a", "b", None], dtype=string_dtype),
  170. }
  171. )
  172. if dtype_backend == "pyarrow":
  173. import pyarrow as pa
  174. from pandas.arrays import ArrowExtensionArray
  175. expected = DataFrame(
  176. {
  177. col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))
  178. for col in expected.columns
  179. }
  180. )
  181. # the storage of the str columns' Index is also affected by the
  182. # string_storage setting -> ignore that for checking the result
  183. tm.assert_frame_equal(result, expected, check_column_type=False)
  184. @pytest.mark.network
  185. @pytest.mark.single_cpu
  186. def test_banklist_url(self, httpserver, banklist_data, flavor_read_html):
  187. with open(banklist_data, encoding="utf-8") as f:
  188. httpserver.serve_content(content=f.read())
  189. df1 = flavor_read_html(
  190. # lxml cannot find attrs leave out for now
  191. httpserver.url,
  192. match="First Federal Bank of Florida", # attrs={"class": "dataTable"}
  193. )
  194. # lxml cannot find attrs leave out for now
  195. df2 = flavor_read_html(
  196. httpserver.url,
  197. match="Metcalf Bank",
  198. ) # attrs={"class": "dataTable"})
  199. assert_framelist_equal(df1, df2)
  200. @pytest.mark.network
  201. @pytest.mark.single_cpu
  202. def test_spam_url(self, httpserver, spam_data, flavor_read_html):
  203. with open(spam_data, encoding="utf-8") as f:
  204. httpserver.serve_content(content=f.read())
  205. df1 = flavor_read_html(httpserver.url, match=".*Water.*")
  206. df2 = flavor_read_html(httpserver.url, match="Unit")
  207. assert_framelist_equal(df1, df2)
  208. @pytest.mark.slow
  209. def test_banklist(self, banklist_data, flavor_read_html):
  210. df1 = flavor_read_html(
  211. banklist_data, match=".*Florida.*", attrs={"id": "table"}
  212. )
  213. df2 = flavor_read_html(
  214. banklist_data, match="Metcalf Bank", attrs={"id": "table"}
  215. )
  216. assert_framelist_equal(df1, df2)
  217. def test_spam(self, spam_data, flavor_read_html):
  218. df1 = flavor_read_html(spam_data, match=".*Water.*")
  219. df2 = flavor_read_html(spam_data, match="Unit")
  220. assert_framelist_equal(df1, df2)
  221. assert df1[0].iloc[0, 0] == "Proximates"
  222. assert df1[0].columns[0] == "Nutrient"
  223. def test_spam_no_match(self, spam_data, flavor_read_html):
  224. dfs = flavor_read_html(spam_data)
  225. for df in dfs:
  226. assert isinstance(df, DataFrame)
  227. def test_banklist_no_match(self, banklist_data, flavor_read_html):
  228. dfs = flavor_read_html(banklist_data, attrs={"id": "table"})
  229. for df in dfs:
  230. assert isinstance(df, DataFrame)
  231. def test_spam_header(self, spam_data, flavor_read_html):
  232. df = flavor_read_html(spam_data, match=".*Water.*", header=2)[0]
  233. assert df.columns[0] == "Proximates"
  234. assert not df.empty
  235. def test_skiprows_int(self, spam_data, flavor_read_html):
  236. df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=1)
  237. df2 = flavor_read_html(spam_data, match="Unit", skiprows=1)
  238. assert_framelist_equal(df1, df2)
  239. def test_skiprows_range(self, spam_data, flavor_read_html):
  240. df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=range(2))
  241. df2 = flavor_read_html(spam_data, match="Unit", skiprows=range(2))
  242. assert_framelist_equal(df1, df2)
  243. def test_skiprows_list(self, spam_data, flavor_read_html):
  244. df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=[1, 2])
  245. df2 = flavor_read_html(spam_data, match="Unit", skiprows=[2, 1])
  246. assert_framelist_equal(df1, df2)
  247. def test_skiprows_set(self, spam_data, flavor_read_html):
  248. df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows={1, 2})
  249. df2 = flavor_read_html(spam_data, match="Unit", skiprows={2, 1})
  250. assert_framelist_equal(df1, df2)
  251. def test_skiprows_slice(self, spam_data, flavor_read_html):
  252. df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=1)
  253. df2 = flavor_read_html(spam_data, match="Unit", skiprows=1)
  254. assert_framelist_equal(df1, df2)
  255. def test_skiprows_slice_short(self, spam_data, flavor_read_html):
  256. df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=slice(2))
  257. df2 = flavor_read_html(spam_data, match="Unit", skiprows=slice(2))
  258. assert_framelist_equal(df1, df2)
  259. def test_skiprows_slice_long(self, spam_data, flavor_read_html):
  260. df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=slice(2, 5))
  261. df2 = flavor_read_html(spam_data, match="Unit", skiprows=slice(4, 1, -1))
  262. assert_framelist_equal(df1, df2)
  263. def test_skiprows_ndarray(self, spam_data, flavor_read_html):
  264. df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=np.arange(2))
  265. df2 = flavor_read_html(spam_data, match="Unit", skiprows=np.arange(2))
  266. assert_framelist_equal(df1, df2)
  267. def test_skiprows_invalid(self, spam_data, flavor_read_html):
  268. with pytest.raises(TypeError, match=("is not a valid type for skipping rows")):
  269. flavor_read_html(spam_data, match=".*Water.*", skiprows="asdf")
  270. def test_index(self, spam_data, flavor_read_html):
  271. df1 = flavor_read_html(spam_data, match=".*Water.*", index_col=0)
  272. df2 = flavor_read_html(spam_data, match="Unit", index_col=0)
  273. assert_framelist_equal(df1, df2)
  274. def test_header_and_index_no_types(self, spam_data, flavor_read_html):
  275. df1 = flavor_read_html(spam_data, match=".*Water.*", header=1, index_col=0)
  276. df2 = flavor_read_html(spam_data, match="Unit", header=1, index_col=0)
  277. assert_framelist_equal(df1, df2)
  278. def test_header_and_index_with_types(self, spam_data, flavor_read_html):
  279. df1 = flavor_read_html(spam_data, match=".*Water.*", header=1, index_col=0)
  280. df2 = flavor_read_html(spam_data, match="Unit", header=1, index_col=0)
  281. assert_framelist_equal(df1, df2)
  282. def test_infer_types(self, spam_data, flavor_read_html):
  283. # 10892 infer_types removed
  284. df1 = flavor_read_html(spam_data, match=".*Water.*", index_col=0)
  285. df2 = flavor_read_html(spam_data, match="Unit", index_col=0)
  286. assert_framelist_equal(df1, df2)
  287. def test_string_io(self, spam_data, flavor_read_html):
  288. with open(spam_data, encoding="UTF-8") as f:
  289. data1 = StringIO(f.read())
  290. with open(spam_data, encoding="UTF-8") as f:
  291. data2 = StringIO(f.read())
  292. df1 = flavor_read_html(data1, match=".*Water.*")
  293. df2 = flavor_read_html(data2, match="Unit")
  294. assert_framelist_equal(df1, df2)
  295. def test_string(self, spam_data, flavor_read_html):
  296. with open(spam_data, encoding="UTF-8") as f:
  297. data = f.read()
  298. df1 = flavor_read_html(StringIO(data), match=".*Water.*")
  299. df2 = flavor_read_html(StringIO(data), match="Unit")
  300. assert_framelist_equal(df1, df2)
  301. def test_file_like(self, spam_data, flavor_read_html):
  302. with open(spam_data, encoding="UTF-8") as f:
  303. df1 = flavor_read_html(f, match=".*Water.*")
  304. with open(spam_data, encoding="UTF-8") as f:
  305. df2 = flavor_read_html(f, match="Unit")
  306. assert_framelist_equal(df1, df2)
  307. @pytest.mark.network
  308. @pytest.mark.single_cpu
  309. def test_bad_url_protocol(self, httpserver, flavor_read_html):
  310. httpserver.serve_content("urlopen error unknown url type: git", code=404)
  311. with pytest.raises(URLError, match="urlopen error unknown url type: git"):
  312. flavor_read_html("git://github.com", match=".*Water.*")
  313. @pytest.mark.slow
  314. @pytest.mark.network
  315. @pytest.mark.single_cpu
  316. def test_invalid_url(self, httpserver, flavor_read_html):
  317. httpserver.serve_content("Name or service not known", code=404)
  318. with pytest.raises((URLError, ValueError), match="HTTP Error 404: NOT FOUND"):
  319. flavor_read_html(httpserver.url, match=".*Water.*")
  320. @pytest.mark.slow
  321. def test_file_url(self, banklist_data, flavor_read_html):
  322. url = banklist_data
  323. dfs = flavor_read_html(
  324. file_path_to_url(os.path.abspath(url)), match="First", attrs={"id": "table"}
  325. )
  326. assert isinstance(dfs, list)
  327. for df in dfs:
  328. assert isinstance(df, DataFrame)
  329. @pytest.mark.slow
  330. def test_invalid_table_attrs(self, banklist_data, flavor_read_html):
  331. url = banklist_data
  332. with pytest.raises(ValueError, match="No tables found"):
  333. flavor_read_html(
  334. url, match="First Federal Bank of Florida", attrs={"id": "tasdfable"}
  335. )
  336. @pytest.mark.slow
  337. def test_multiindex_header(self, banklist_data, flavor_read_html):
  338. df = flavor_read_html(
  339. banklist_data, match="Metcalf", attrs={"id": "table"}, header=[0, 1]
  340. )[0]
  341. assert isinstance(df.columns, MultiIndex)
  342. @pytest.mark.slow
  343. def test_multiindex_index(self, banklist_data, flavor_read_html):
  344. df = flavor_read_html(
  345. banklist_data, match="Metcalf", attrs={"id": "table"}, index_col=[0, 1]
  346. )[0]
  347. assert isinstance(df.index, MultiIndex)
  348. @pytest.mark.slow
  349. def test_multiindex_header_index(self, banklist_data, flavor_read_html):
  350. df = flavor_read_html(
  351. banklist_data,
  352. match="Metcalf",
  353. attrs={"id": "table"},
  354. header=[0, 1],
  355. index_col=[0, 1],
  356. )[0]
  357. assert isinstance(df.columns, MultiIndex)
  358. assert isinstance(df.index, MultiIndex)
  359. @pytest.mark.slow
  360. def test_multiindex_header_skiprows_tuples(self, banklist_data, flavor_read_html):
  361. df = flavor_read_html(
  362. banklist_data,
  363. match="Metcalf",
  364. attrs={"id": "table"},
  365. header=[0, 1],
  366. skiprows=1,
  367. )[0]
  368. assert isinstance(df.columns, MultiIndex)
  369. @pytest.mark.slow
  370. def test_multiindex_header_skiprows(self, banklist_data, flavor_read_html):
  371. df = flavor_read_html(
  372. banklist_data,
  373. match="Metcalf",
  374. attrs={"id": "table"},
  375. header=[0, 1],
  376. skiprows=1,
  377. )[0]
  378. assert isinstance(df.columns, MultiIndex)
  379. @pytest.mark.slow
  380. def test_multiindex_header_index_skiprows(self, banklist_data, flavor_read_html):
  381. df = flavor_read_html(
  382. banklist_data,
  383. match="Metcalf",
  384. attrs={"id": "table"},
  385. header=[0, 1],
  386. index_col=[0, 1],
  387. skiprows=1,
  388. )[0]
  389. assert isinstance(df.index, MultiIndex)
  390. assert isinstance(df.columns, MultiIndex)
  391. @pytest.mark.slow
  392. def test_regex_idempotency(self, banklist_data, flavor_read_html):
  393. url = banklist_data
  394. dfs = flavor_read_html(
  395. file_path_to_url(os.path.abspath(url)),
  396. match=re.compile(re.compile("Florida")),
  397. attrs={"id": "table"},
  398. )
  399. assert isinstance(dfs, list)
  400. for df in dfs:
  401. assert isinstance(df, DataFrame)
  402. def test_negative_skiprows(self, spam_data, flavor_read_html):
  403. msg = r"\(you passed a negative value\)"
  404. with pytest.raises(ValueError, match=msg):
  405. flavor_read_html(spam_data, match="Water", skiprows=-1)
  406. @pytest.fixture
  407. def python_docs(self):
  408. return """
  409. <table class="contentstable" align="center"><tr>
  410. <td width="50%">
  411. <p class="biglink"><a class="biglink" href="whatsnew/2.7.html">What's new in Python 2.7?</a><br/>
  412. <span class="linkdescr">or <a href="whatsnew/index.html">all "What's new" documents</a> since 2.0</span></p>
  413. <p class="biglink"><a class="biglink" href="tutorial/index.html">Tutorial</a><br/>
  414. <span class="linkdescr">start here</span></p>
  415. <p class="biglink"><a class="biglink" href="library/index.html">Library Reference</a><br/>
  416. <span class="linkdescr">keep this under your pillow</span></p>
  417. <p class="biglink"><a class="biglink" href="reference/index.html">Language Reference</a><br/>
  418. <span class="linkdescr">describes syntax and language elements</span></p>
  419. <p class="biglink"><a class="biglink" href="using/index.html">Python Setup and Usage</a><br/>
  420. <span class="linkdescr">how to use Python on different platforms</span></p>
  421. <p class="biglink"><a class="biglink" href="howto/index.html">Python HOWTOs</a><br/>
  422. <span class="linkdescr">in-depth documents on specific topics</span></p>
  423. </td><td width="50%">
  424. <p class="biglink"><a class="biglink" href="installing/index.html">Installing Python Modules</a><br/>
  425. <span class="linkdescr">installing from the Python Package Index &amp; other sources</span></p>
  426. <p class="biglink"><a class="biglink" href="distributing/index.html">Distributing Python Modules</a><br/>
  427. <span class="linkdescr">publishing modules for installation by others</span></p>
  428. <p class="biglink"><a class="biglink" href="extending/index.html">Extending and Embedding</a><br/>
  429. <span class="linkdescr">tutorial for C/C++ programmers</span></p>
  430. <p class="biglink"><a class="biglink" href="c-api/index.html">Python/C API</a><br/>
  431. <span class="linkdescr">reference for C/C++ programmers</span></p>
  432. <p class="biglink"><a class="biglink" href="faq/index.html">FAQs</a><br/>
  433. <span class="linkdescr">frequently asked questions (with answers!)</span></p>
  434. </td></tr>
  435. </table>
  436. <p><strong>Indices and tables:</strong></p>
  437. <table class="contentstable" align="center"><tr>
  438. <td width="50%">
  439. <p class="biglink"><a class="biglink" href="py-modindex.html">Python Global Module Index</a><br/>
  440. <span class="linkdescr">quick access to all modules</span></p>
  441. <p class="biglink"><a class="biglink" href="genindex.html">General Index</a><br/>
  442. <span class="linkdescr">all functions, classes, terms</span></p>
  443. <p class="biglink"><a class="biglink" href="glossary.html">Glossary</a><br/>
  444. <span class="linkdescr">the most important terms explained</span></p>
  445. </td><td width="50%">
  446. <p class="biglink"><a class="biglink" href="search.html">Search page</a><br/>
  447. <span class="linkdescr">search this documentation</span></p>
  448. <p class="biglink"><a class="biglink" href="contents.html">Complete Table of Contents</a><br/>
  449. <span class="linkdescr">lists all sections and subsections</span></p>
  450. </td></tr>
  451. </table>
  452. """ # noqa: E501
  453. @pytest.mark.network
  454. @pytest.mark.single_cpu
  455. def test_multiple_matches(self, python_docs, httpserver, flavor_read_html):
  456. httpserver.serve_content(content=python_docs)
  457. dfs = flavor_read_html(httpserver.url, match="Python")
  458. assert len(dfs) > 1
  459. @pytest.mark.network
  460. @pytest.mark.single_cpu
  461. def test_python_docs_table(self, python_docs, httpserver, flavor_read_html):
  462. httpserver.serve_content(content=python_docs)
  463. dfs = flavor_read_html(httpserver.url, match="Python")
  464. zz = [df.iloc[0, 0][0:4] for df in dfs]
  465. assert sorted(zz) == ["Pyth", "What"]
  466. def test_empty_tables(self, flavor_read_html):
  467. """
  468. Make sure that read_html ignores empty tables.
  469. """
  470. html = """
  471. <table>
  472. <thead>
  473. <tr>
  474. <th>A</th>
  475. <th>B</th>
  476. </tr>
  477. </thead>
  478. <tbody>
  479. <tr>
  480. <td>1</td>
  481. <td>2</td>
  482. </tr>
  483. </tbody>
  484. </table>
  485. <table>
  486. <tbody>
  487. </tbody>
  488. </table>
  489. """
  490. result = flavor_read_html(StringIO(html))
  491. assert len(result) == 1
  492. def test_multiple_tbody(self, flavor_read_html):
  493. # GH-20690
  494. # Read all tbody tags within a single table.
  495. result = flavor_read_html(
  496. StringIO(
  497. """<table>
  498. <thead>
  499. <tr>
  500. <th>A</th>
  501. <th>B</th>
  502. </tr>
  503. </thead>
  504. <tbody>
  505. <tr>
  506. <td>1</td>
  507. <td>2</td>
  508. </tr>
  509. </tbody>
  510. <tbody>
  511. <tr>
  512. <td>3</td>
  513. <td>4</td>
  514. </tr>
  515. </tbody>
  516. </table>"""
  517. )
  518. )[0]
  519. expected = DataFrame(data=[[1, 2], [3, 4]], columns=["A", "B"])
  520. tm.assert_frame_equal(result, expected)
  521. def test_header_and_one_column(self, flavor_read_html):
  522. """
  523. Don't fail with bs4 when there is a header and only one column
  524. as described in issue #9178
  525. """
  526. result = flavor_read_html(
  527. StringIO(
  528. """<table>
  529. <thead>
  530. <tr>
  531. <th>Header</th>
  532. </tr>
  533. </thead>
  534. <tbody>
  535. <tr>
  536. <td>first</td>
  537. </tr>
  538. </tbody>
  539. </table>"""
  540. )
  541. )[0]
  542. expected = DataFrame(data={"Header": "first"}, index=[0])
  543. tm.assert_frame_equal(result, expected)
  544. def test_thead_without_tr(self, flavor_read_html):
  545. """
  546. Ensure parser adds <tr> within <thead> on malformed HTML.
  547. """
  548. result = flavor_read_html(
  549. StringIO(
  550. """<table>
  551. <thead>
  552. <tr>
  553. <th>Country</th>
  554. <th>Municipality</th>
  555. <th>Year</th>
  556. </tr>
  557. </thead>
  558. <tbody>
  559. <tr>
  560. <td>Ukraine</td>
  561. <th>Odessa</th>
  562. <td>1944</td>
  563. </tr>
  564. </tbody>
  565. </table>"""
  566. )
  567. )[0]
  568. expected = DataFrame(
  569. data=[["Ukraine", "Odessa", 1944]],
  570. columns=["Country", "Municipality", "Year"],
  571. )
  572. tm.assert_frame_equal(result, expected)
  573. def test_tfoot_read(self, flavor_read_html):
  574. """
  575. Make sure that read_html reads tfoot, containing td or th.
  576. Ignores empty tfoot
  577. """
  578. data_template = """<table>
  579. <thead>
  580. <tr>
  581. <th>A</th>
  582. <th>B</th>
  583. </tr>
  584. </thead>
  585. <tbody>
  586. <tr>
  587. <td>bodyA</td>
  588. <td>bodyB</td>
  589. </tr>
  590. </tbody>
  591. <tfoot>
  592. {footer}
  593. </tfoot>
  594. </table>"""
  595. expected1 = DataFrame(data=[["bodyA", "bodyB"]], columns=["A", "B"])
  596. expected2 = DataFrame(
  597. data=[["bodyA", "bodyB"], ["footA", "footB"]], columns=["A", "B"]
  598. )
  599. data1 = data_template.format(footer="")
  600. data2 = data_template.format(footer="<tr><td>footA</td><th>footB</th></tr>")
  601. result1 = flavor_read_html(StringIO(data1))[0]
  602. result2 = flavor_read_html(StringIO(data2))[0]
  603. tm.assert_frame_equal(result1, expected1)
  604. tm.assert_frame_equal(result2, expected2)
  605. def test_parse_header_of_non_string_column(self, flavor_read_html):
  606. # GH5048: if header is specified explicitly, an int column should be
  607. # parsed as int while its header is parsed as str
  608. result = flavor_read_html(
  609. StringIO(
  610. """
  611. <table>
  612. <tr>
  613. <td>S</td>
  614. <td>I</td>
  615. </tr>
  616. <tr>
  617. <td>text</td>
  618. <td>1944</td>
  619. </tr>
  620. </table>
  621. """
  622. ),
  623. header=0,
  624. )[0]
  625. expected = DataFrame([["text", 1944]], columns=("S", "I"))
  626. tm.assert_frame_equal(result, expected)
  627. @pytest.mark.slow
  628. def test_banklist_header(self, banklist_data, datapath, flavor_read_html):
  629. from pandas.io.html import _remove_whitespace
  630. def try_remove_ws(x):
  631. try:
  632. return _remove_whitespace(x)
  633. except AttributeError:
  634. return x
  635. df = flavor_read_html(banklist_data, match="Metcalf", attrs={"id": "table"})[0]
  636. ground_truth = read_csv(
  637. datapath("io", "data", "csv", "banklist.csv"),
  638. converters={"Updated Date": Timestamp, "Closing Date": Timestamp},
  639. )
  640. assert df.shape == ground_truth.shape
  641. old = [
  642. "First Vietnamese American Bank In Vietnamese",
  643. "Westernbank Puerto Rico En Espanol",
  644. "R-G Premier Bank of Puerto Rico En Espanol",
  645. "Eurobank En Espanol",
  646. "Sanderson State Bank En Espanol",
  647. "Washington Mutual Bank (Including its subsidiary Washington "
  648. "Mutual Bank FSB)",
  649. "Silver State Bank En Espanol",
  650. "AmTrade International Bank En Espanol",
  651. "Hamilton Bank, NA En Espanol",
  652. "The Citizens Savings Bank Pioneer Community Bank, Inc.",
  653. ]
  654. new = [
  655. "First Vietnamese American Bank",
  656. "Westernbank Puerto Rico",
  657. "R-G Premier Bank of Puerto Rico",
  658. "Eurobank",
  659. "Sanderson State Bank",
  660. "Washington Mutual Bank",
  661. "Silver State Bank",
  662. "AmTrade International Bank",
  663. "Hamilton Bank, NA",
  664. "The Citizens Savings Bank",
  665. ]
  666. dfnew = df.map(try_remove_ws).replace(old, new)
  667. gtnew = ground_truth.map(try_remove_ws)
  668. converted = dfnew
  669. date_cols = ["Closing Date", "Updated Date"]
  670. converted[date_cols] = converted[date_cols].apply(to_datetime)
  671. tm.assert_frame_equal(converted, gtnew)
  672. @pytest.mark.slow
  673. def test_gold_canyon(self, banklist_data, flavor_read_html):
  674. gc = "Gold Canyon"
  675. with open(banklist_data, encoding="utf-8") as f:
  676. raw_text = f.read()
  677. assert gc in raw_text
  678. df = flavor_read_html(
  679. banklist_data, match="Gold Canyon", attrs={"id": "table"}
  680. )[0]
  681. assert gc in df.to_string()
  682. def test_different_number_of_cols(self, flavor_read_html):
  683. expected = flavor_read_html(
  684. StringIO(
  685. """<table>
  686. <thead>
  687. <tr style="text-align: right;">
  688. <th></th>
  689. <th>C_l0_g0</th>
  690. <th>C_l0_g1</th>
  691. <th>C_l0_g2</th>
  692. <th>C_l0_g3</th>
  693. <th>C_l0_g4</th>
  694. </tr>
  695. </thead>
  696. <tbody>
  697. <tr>
  698. <th>R_l0_g0</th>
  699. <td> 0.763</td>
  700. <td> 0.233</td>
  701. <td> nan</td>
  702. <td> nan</td>
  703. <td> nan</td>
  704. </tr>
  705. <tr>
  706. <th>R_l0_g1</th>
  707. <td> 0.244</td>
  708. <td> 0.285</td>
  709. <td> 0.392</td>
  710. <td> 0.137</td>
  711. <td> 0.222</td>
  712. </tr>
  713. </tbody>
  714. </table>"""
  715. ),
  716. index_col=0,
  717. )[0]
  718. result = flavor_read_html(
  719. StringIO(
  720. """<table>
  721. <thead>
  722. <tr style="text-align: right;">
  723. <th></th>
  724. <th>C_l0_g0</th>
  725. <th>C_l0_g1</th>
  726. <th>C_l0_g2</th>
  727. <th>C_l0_g3</th>
  728. <th>C_l0_g4</th>
  729. </tr>
  730. </thead>
  731. <tbody>
  732. <tr>
  733. <th>R_l0_g0</th>
  734. <td> 0.763</td>
  735. <td> 0.233</td>
  736. </tr>
  737. <tr>
  738. <th>R_l0_g1</th>
  739. <td> 0.244</td>
  740. <td> 0.285</td>
  741. <td> 0.392</td>
  742. <td> 0.137</td>
  743. <td> 0.222</td>
  744. </tr>
  745. </tbody>
  746. </table>"""
  747. ),
  748. index_col=0,
  749. )[0]
  750. tm.assert_frame_equal(result, expected)
  751. def test_colspan_rowspan_1(self, flavor_read_html):
  752. # GH17054
  753. result = flavor_read_html(
  754. StringIO(
  755. """
  756. <table>
  757. <tr>
  758. <th>A</th>
  759. <th colspan="1">B</th>
  760. <th rowspan="1">C</th>
  761. </tr>
  762. <tr>
  763. <td>a</td>
  764. <td>b</td>
  765. <td>c</td>
  766. </tr>
  767. </table>
  768. """
  769. )
  770. )[0]
  771. expected = DataFrame([["a", "b", "c"]], columns=["A", "B", "C"])
  772. tm.assert_frame_equal(result, expected)
  773. def test_colspan_rowspan_copy_values(self, flavor_read_html):
  774. # GH17054
  775. # In ASCII, with lowercase letters being copies:
  776. #
  777. # X x Y Z W
  778. # A B b z C
  779. result = flavor_read_html(
  780. StringIO(
  781. """
  782. <table>
  783. <tr>
  784. <td colspan="2">X</td>
  785. <td>Y</td>
  786. <td rowspan="2">Z</td>
  787. <td>W</td>
  788. </tr>
  789. <tr>
  790. <td>A</td>
  791. <td colspan="2">B</td>
  792. <td>C</td>
  793. </tr>
  794. </table>
  795. """
  796. ),
  797. header=0,
  798. )[0]
  799. expected = DataFrame(
  800. data=[["A", "B", "B", "Z", "C"]], columns=["X", "X.1", "Y", "Z", "W"]
  801. )
  802. tm.assert_frame_equal(result, expected)
  803. def test_colspan_rowspan_both_not_1(self, flavor_read_html):
  804. # GH17054
  805. # In ASCII, with lowercase letters being copies:
  806. #
  807. # A B b b C
  808. # a b b b D
  809. result = flavor_read_html(
  810. StringIO(
  811. """
  812. <table>
  813. <tr>
  814. <td rowspan="2">A</td>
  815. <td rowspan="2" colspan="3">B</td>
  816. <td>C</td>
  817. </tr>
  818. <tr>
  819. <td>D</td>
  820. </tr>
  821. </table>
  822. """
  823. ),
  824. header=0,
  825. )[0]
  826. expected = DataFrame(
  827. data=[["A", "B", "B", "B", "D"]], columns=["A", "B", "B.1", "B.2", "C"]
  828. )
  829. tm.assert_frame_equal(result, expected)
  830. def test_rowspan_at_end_of_row(self, flavor_read_html):
  831. # GH17054
  832. # In ASCII, with lowercase letters being copies:
  833. #
  834. # A B
  835. # C b
  836. result = flavor_read_html(
  837. StringIO(
  838. """
  839. <table>
  840. <tr>
  841. <td>A</td>
  842. <td rowspan="2">B</td>
  843. </tr>
  844. <tr>
  845. <td>C</td>
  846. </tr>
  847. </table>
  848. """
  849. ),
  850. header=0,
  851. )[0]
  852. expected = DataFrame(data=[["C", "B"]], columns=["A", "B"])
  853. tm.assert_frame_equal(result, expected)
  854. def test_rowspan_only_rows(self, flavor_read_html):
  855. # GH17054
  856. result = flavor_read_html(
  857. StringIO(
  858. """
  859. <table>
  860. <tr>
  861. <td rowspan="3">A</td>
  862. <td rowspan="3">B</td>
  863. </tr>
  864. </table>
  865. """
  866. ),
  867. header=0,
  868. )[0]
  869. expected = DataFrame(data=[["A", "B"], ["A", "B"]], columns=["A", "B"])
  870. tm.assert_frame_equal(result, expected)
  871. def test_header_inferred_from_rows_with_only_th(self, flavor_read_html):
  872. # GH17054
  873. result = flavor_read_html(
  874. StringIO(
  875. """
  876. <table>
  877. <tr>
  878. <th>A</th>
  879. <th>B</th>
  880. </tr>
  881. <tr>
  882. <th>a</th>
  883. <th>b</th>
  884. </tr>
  885. <tr>
  886. <td>1</td>
  887. <td>2</td>
  888. </tr>
  889. </table>
  890. """
  891. )
  892. )[0]
  893. columns = MultiIndex(levels=[["A", "B"], ["a", "b"]], codes=[[0, 1], [0, 1]])
  894. expected = DataFrame(data=[[1, 2]], columns=columns)
  895. tm.assert_frame_equal(result, expected)
  896. def test_parse_dates_list(self, flavor_read_html):
  897. df = DataFrame({"date": date_range("1/1/2001", periods=10)})
  898. expected = df.to_html()
  899. res = flavor_read_html(StringIO(expected), parse_dates=[1], index_col=0)
  900. tm.assert_frame_equal(df, res[0])
  901. res = flavor_read_html(StringIO(expected), parse_dates=["date"], index_col=0)
  902. tm.assert_frame_equal(df, res[0])
  903. def test_parse_dates_combine(self, flavor_read_html):
  904. raw_dates = Series(date_range("1/1/2001", periods=10))
  905. df = DataFrame(
  906. {
  907. "date": raw_dates.map(lambda x: str(x.date())),
  908. "time": raw_dates.map(lambda x: str(x.time())),
  909. }
  910. )
  911. res = flavor_read_html(
  912. StringIO(df.to_html()), parse_dates={"datetime": [1, 2]}, index_col=1
  913. )
  914. newdf = DataFrame({"datetime": raw_dates})
  915. tm.assert_frame_equal(newdf, res[0])
  916. def test_wikipedia_states_table(self, datapath, flavor_read_html):
  917. data = datapath("io", "data", "html", "wikipedia_states.html")
  918. assert os.path.isfile(data), f"{repr(data)} is not a file"
  919. assert os.path.getsize(data), f"{repr(data)} is an empty file"
  920. result = flavor_read_html(data, match="Arizona", header=1)[0]
  921. assert result.shape == (60, 12)
  922. assert "Unnamed" in result.columns[-1]
  923. assert result["sq mi"].dtype == np.dtype("float64")
  924. assert np.allclose(result.loc[0, "sq mi"], 665384.04)
  925. def test_wikipedia_states_multiindex(self, datapath, flavor_read_html):
  926. data = datapath("io", "data", "html", "wikipedia_states.html")
  927. result = flavor_read_html(data, match="Arizona", index_col=0)[0]
  928. assert result.shape == (60, 11)
  929. assert "Unnamed" in result.columns[-1][1]
  930. assert result.columns.nlevels == 2
  931. assert np.allclose(result.loc["Alaska", ("Total area[2]", "sq mi")], 665384.04)
  932. def test_parser_error_on_empty_header_row(self, flavor_read_html):
  933. result = flavor_read_html(
  934. StringIO(
  935. """
  936. <table>
  937. <thead>
  938. <tr><th></th><th></tr>
  939. <tr><th>A</th><th>B</th></tr>
  940. </thead>
  941. <tbody>
  942. <tr><td>a</td><td>b</td></tr>
  943. </tbody>
  944. </table>
  945. """
  946. ),
  947. header=[0, 1],
  948. )
  949. expected = DataFrame(
  950. [["a", "b"]],
  951. columns=MultiIndex.from_tuples(
  952. [("Unnamed: 0_level_0", "A"), ("Unnamed: 1_level_0", "B")]
  953. ),
  954. )
  955. tm.assert_frame_equal(result[0], expected)
  956. def test_decimal_rows(self, flavor_read_html):
  957. # GH 12907
  958. result = flavor_read_html(
  959. StringIO(
  960. """<html>
  961. <body>
  962. <table>
  963. <thead>
  964. <tr>
  965. <th>Header</th>
  966. </tr>
  967. </thead>
  968. <tbody>
  969. <tr>
  970. <td>1100#101</td>
  971. </tr>
  972. </tbody>
  973. </table>
  974. </body>
  975. </html>"""
  976. ),
  977. decimal="#",
  978. )[0]
  979. expected = DataFrame(data={"Header": 1100.101}, index=[0])
  980. assert result["Header"].dtype == np.dtype("float64")
  981. tm.assert_frame_equal(result, expected)
  982. @pytest.mark.parametrize("arg", [True, False])
  983. def test_bool_header_arg(self, spam_data, arg, flavor_read_html):
  984. # GH 6114
  985. msg = re.escape(
  986. "Passing a bool to header is invalid. Use header=None for no header or "
  987. "header=int or list-like of ints to specify the row(s) making up the "
  988. "column names"
  989. )
  990. with pytest.raises(TypeError, match=msg):
  991. flavor_read_html(spam_data, header=arg)
  992. def test_converters(self, flavor_read_html):
  993. # GH 13461
  994. result = flavor_read_html(
  995. StringIO(
  996. """<table>
  997. <thead>
  998. <tr>
  999. <th>a</th>
  1000. </tr>
  1001. </thead>
  1002. <tbody>
  1003. <tr>
  1004. <td> 0.763</td>
  1005. </tr>
  1006. <tr>
  1007. <td> 0.244</td>
  1008. </tr>
  1009. </tbody>
  1010. </table>"""
  1011. ),
  1012. converters={"a": str},
  1013. )[0]
  1014. expected = DataFrame({"a": ["0.763", "0.244"]})
  1015. tm.assert_frame_equal(result, expected)
  1016. def test_na_values(self, flavor_read_html):
  1017. # GH 13461
  1018. result = flavor_read_html(
  1019. StringIO(
  1020. """<table>
  1021. <thead>
  1022. <tr>
  1023. <th>a</th>
  1024. </tr>
  1025. </thead>
  1026. <tbody>
  1027. <tr>
  1028. <td> 0.763</td>
  1029. </tr>
  1030. <tr>
  1031. <td> 0.244</td>
  1032. </tr>
  1033. </tbody>
  1034. </table>"""
  1035. ),
  1036. na_values=[0.244],
  1037. )[0]
  1038. expected = DataFrame({"a": [0.763, np.nan]})
  1039. tm.assert_frame_equal(result, expected)
  1040. def test_keep_default_na(self, flavor_read_html):
  1041. html_data = """<table>
  1042. <thead>
  1043. <tr>
  1044. <th>a</th>
  1045. </tr>
  1046. </thead>
  1047. <tbody>
  1048. <tr>
  1049. <td> N/A</td>
  1050. </tr>
  1051. <tr>
  1052. <td> NA</td>
  1053. </tr>
  1054. </tbody>
  1055. </table>"""
  1056. expected_df = DataFrame({"a": ["N/A", "NA"]})
  1057. html_df = flavor_read_html(StringIO(html_data), keep_default_na=False)[0]
  1058. tm.assert_frame_equal(expected_df, html_df)
  1059. expected_df = DataFrame({"a": [np.nan, np.nan]})
  1060. html_df = flavor_read_html(StringIO(html_data), keep_default_na=True)[0]
  1061. tm.assert_frame_equal(expected_df, html_df)
  1062. def test_preserve_empty_rows(self, flavor_read_html):
  1063. result = flavor_read_html(
  1064. StringIO(
  1065. """
  1066. <table>
  1067. <tr>
  1068. <th>A</th>
  1069. <th>B</th>
  1070. </tr>
  1071. <tr>
  1072. <td>a</td>
  1073. <td>b</td>
  1074. </tr>
  1075. <tr>
  1076. <td></td>
  1077. <td></td>
  1078. </tr>
  1079. </table>
  1080. """
  1081. )
  1082. )[0]
  1083. expected = DataFrame(data=[["a", "b"], [np.nan, np.nan]], columns=["A", "B"])
  1084. tm.assert_frame_equal(result, expected)
  1085. def test_ignore_empty_rows_when_inferring_header(self, flavor_read_html):
  1086. result = flavor_read_html(
  1087. StringIO(
  1088. """
  1089. <table>
  1090. <thead>
  1091. <tr><th></th><th></tr>
  1092. <tr><th>A</th><th>B</th></tr>
  1093. <tr><th>a</th><th>b</th></tr>
  1094. </thead>
  1095. <tbody>
  1096. <tr><td>1</td><td>2</td></tr>
  1097. </tbody>
  1098. </table>
  1099. """
  1100. )
  1101. )[0]
  1102. columns = MultiIndex(levels=[["A", "B"], ["a", "b"]], codes=[[0, 1], [0, 1]])
  1103. expected = DataFrame(data=[[1, 2]], columns=columns)
  1104. tm.assert_frame_equal(result, expected)
  1105. def test_multiple_header_rows(self, flavor_read_html):
  1106. # Issue #13434
  1107. expected_df = DataFrame(
  1108. data=[("Hillary", 68, "D"), ("Bernie", 74, "D"), ("Donald", 69, "R")]
  1109. )
  1110. expected_df.columns = [
  1111. ["Unnamed: 0_level_0", "Age", "Party"],
  1112. ["Name", "Unnamed: 1_level_1", "Unnamed: 2_level_1"],
  1113. ]
  1114. html = expected_df.to_html(index=False)
  1115. html_df = flavor_read_html(StringIO(html))[0]
  1116. tm.assert_frame_equal(expected_df, html_df)
  1117. def test_works_on_valid_markup(self, datapath, flavor_read_html):
  1118. filename = datapath("io", "data", "html", "valid_markup.html")
  1119. dfs = flavor_read_html(filename, index_col=0)
  1120. assert isinstance(dfs, list)
  1121. assert isinstance(dfs[0], DataFrame)
  1122. @pytest.mark.slow
  1123. def test_fallback_success(self, datapath, flavor_read_html):
  1124. banklist_data = datapath("io", "data", "html", "banklist.html")
  1125. flavor_read_html(banklist_data, match=".*Water.*", flavor=["lxml", "html5lib"])
  1126. def test_to_html_timestamp(self):
  1127. rng = date_range("2000-01-01", periods=10)
  1128. df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)), index=rng)
  1129. result = df.to_html()
  1130. assert "2000-01-01" in result
  1131. def test_to_html_borderless(self):
  1132. df = DataFrame([{"A": 1, "B": 2}])
  1133. out_border_default = df.to_html()
  1134. out_border_true = df.to_html(border=True)
  1135. out_border_explicit_default = df.to_html(border=1)
  1136. out_border_nondefault = df.to_html(border=2)
  1137. out_border_zero = df.to_html(border=0)
  1138. out_border_false = df.to_html(border=False)
  1139. assert ' border="1"' in out_border_default
  1140. assert out_border_true == out_border_default
  1141. assert out_border_default == out_border_explicit_default
  1142. assert out_border_default != out_border_nondefault
  1143. assert ' border="2"' in out_border_nondefault
  1144. assert ' border="0"' not in out_border_zero
  1145. assert " border" not in out_border_false
  1146. assert out_border_zero == out_border_false
  1147. @pytest.mark.parametrize(
  1148. "displayed_only,exp0,exp1",
  1149. [
  1150. (True, DataFrame(["foo"]), None),
  1151. (False, DataFrame(["foo bar baz qux"]), DataFrame(["foo"])),
  1152. ],
  1153. )
  1154. def test_displayed_only(self, displayed_only, exp0, exp1, flavor_read_html):
  1155. # GH 20027
  1156. data = """<html>
  1157. <body>
  1158. <table>
  1159. <tr>
  1160. <td>
  1161. foo
  1162. <span style="display:none;text-align:center">bar</span>
  1163. <span style="display:none">baz</span>
  1164. <span style="display: none">qux</span>
  1165. </td>
  1166. </tr>
  1167. </table>
  1168. <table style="display: none">
  1169. <tr>
  1170. <td>foo</td>
  1171. </tr>
  1172. </table>
  1173. </body>
  1174. </html>"""
  1175. dfs = flavor_read_html(StringIO(data), displayed_only=displayed_only)
  1176. tm.assert_frame_equal(dfs[0], exp0)
  1177. if exp1 is not None:
  1178. tm.assert_frame_equal(dfs[1], exp1)
  1179. else:
  1180. assert len(dfs) == 1 # Should not parse hidden table
  1181. @pytest.mark.parametrize("displayed_only", [True, False])
  1182. def test_displayed_only_with_many_elements(self, displayed_only, flavor_read_html):
  1183. html_table = """
  1184. <table>
  1185. <tr>
  1186. <th>A</th>
  1187. <th>B</th>
  1188. </tr>
  1189. <tr>
  1190. <td>1</td>
  1191. <td>2</td>
  1192. </tr>
  1193. <tr>
  1194. <td><span style="display:none"></span>4</td>
  1195. <td>5</td>
  1196. </tr>
  1197. </table>
  1198. """
  1199. result = flavor_read_html(StringIO(html_table), displayed_only=displayed_only)[
  1200. 0
  1201. ]
  1202. expected = DataFrame({"A": [1, 4], "B": [2, 5]})
  1203. tm.assert_frame_equal(result, expected)
  1204. @td.skip_if_windows()
  1205. @pytest.mark.filterwarnings(
  1206. "ignore:You provided Unicode markup but also provided a value for "
  1207. "from_encoding.*:UserWarning"
  1208. )
  1209. def test_encode(self, html_encoding_file, flavor_read_html):
  1210. base_path = os.path.basename(html_encoding_file)
  1211. root = os.path.splitext(base_path)[0]
  1212. _, encoding = root.split("_")
  1213. try:
  1214. with open(html_encoding_file, "rb") as fobj:
  1215. from_string = flavor_read_html(
  1216. fobj.read(), encoding=encoding, index_col=0
  1217. ).pop()
  1218. with open(html_encoding_file, "rb") as fobj:
  1219. from_file_like = flavor_read_html(
  1220. BytesIO(fobj.read()), encoding=encoding, index_col=0
  1221. ).pop()
  1222. from_filename = flavor_read_html(
  1223. html_encoding_file, encoding=encoding, index_col=0
  1224. ).pop()
  1225. tm.assert_frame_equal(from_string, from_file_like)
  1226. tm.assert_frame_equal(from_string, from_filename)
  1227. except Exception:
  1228. # seems utf-16/32 fail on windows
  1229. if is_platform_windows():
  1230. if "16" in encoding or "32" in encoding:
  1231. pytest.skip()
  1232. raise
  1233. def test_parse_failure_unseekable(self, flavor_read_html):
  1234. # Issue #17975
  1235. if flavor_read_html.keywords.get("flavor") == "lxml":
  1236. pytest.skip("Not applicable for lxml")
  1237. class UnseekableStringIO(StringIO):
  1238. def seekable(self):
  1239. return False
  1240. bad = UnseekableStringIO(
  1241. """
  1242. <table><tr><td>spam<foobr />eggs</td></tr></table>"""
  1243. )
  1244. assert flavor_read_html(bad)
  1245. with pytest.raises(ValueError, match="passed a non-rewindable file object"):
  1246. flavor_read_html(bad)
  1247. def test_parse_failure_rewinds(self, flavor_read_html):
  1248. # Issue #17975
  1249. class MockFile:
  1250. def __init__(self, data) -> None:
  1251. self.data = data
  1252. self.at_end = False
  1253. def read(self, size=None):
  1254. data = "" if self.at_end else self.data
  1255. self.at_end = True
  1256. return data
  1257. def seek(self, offset):
  1258. self.at_end = False
  1259. def seekable(self):
  1260. return True
  1261. # GH 49036 pylint checks for presence of __next__ for iterators
  1262. def __next__(self):
  1263. ...
  1264. def __iter__(self) -> Iterator:
  1265. # `is_file_like` depends on the presence of
  1266. # the __iter__ attribute.
  1267. return self
  1268. good = MockFile("<table><tr><td>spam<br />eggs</td></tr></table>")
  1269. bad = MockFile("<table><tr><td>spam<foobr />eggs</td></tr></table>")
  1270. assert flavor_read_html(good)
  1271. assert flavor_read_html(bad)
  1272. @pytest.mark.slow
  1273. @pytest.mark.single_cpu
  1274. def test_importcheck_thread_safety(self, datapath, flavor_read_html):
  1275. # see gh-16928
  1276. class ErrorThread(threading.Thread):
  1277. def run(self):
  1278. try:
  1279. super().run()
  1280. except Exception as err:
  1281. self.err = err
  1282. else:
  1283. self.err = None
  1284. filename = datapath("io", "data", "html", "valid_markup.html")
  1285. helper_thread1 = ErrorThread(target=flavor_read_html, args=(filename,))
  1286. helper_thread2 = ErrorThread(target=flavor_read_html, args=(filename,))
  1287. helper_thread1.start()
  1288. helper_thread2.start()
  1289. while helper_thread1.is_alive() or helper_thread2.is_alive():
  1290. pass
  1291. assert None is helper_thread1.err is helper_thread2.err
  1292. def test_parse_path_object(self, datapath, flavor_read_html):
  1293. # GH 37705
  1294. file_path_string = datapath("io", "data", "html", "spam.html")
  1295. file_path = Path(file_path_string)
  1296. df1 = flavor_read_html(file_path_string)[0]
  1297. df2 = flavor_read_html(file_path)[0]
  1298. tm.assert_frame_equal(df1, df2)
  1299. def test_parse_br_as_space(self, flavor_read_html):
  1300. # GH 29528: pd.read_html() convert <br> to space
  1301. result = flavor_read_html(
  1302. StringIO(
  1303. """
  1304. <table>
  1305. <tr>
  1306. <th>A</th>
  1307. </tr>
  1308. <tr>
  1309. <td>word1<br>word2</td>
  1310. </tr>
  1311. </table>
  1312. """
  1313. )
  1314. )[0]
  1315. expected = DataFrame(data=[["word1 word2"]], columns=["A"])
  1316. tm.assert_frame_equal(result, expected)
  1317. @pytest.mark.parametrize("arg", ["all", "body", "header", "footer"])
  1318. def test_extract_links(self, arg, flavor_read_html):
  1319. gh_13141_data = """
  1320. <table>
  1321. <tr>
  1322. <th>HTTP</th>
  1323. <th>FTP</th>
  1324. <th><a href="https://en.wiktionary.org/wiki/linkless">Linkless</a></th>
  1325. </tr>
  1326. <tr>
  1327. <td><a href="https://en.wikipedia.org/">Wikipedia</a></td>
  1328. <td>SURROUNDING <a href="ftp://ftp.us.debian.org/">Debian</a> TEXT</td>
  1329. <td>Linkless</td>
  1330. </tr>
  1331. <tfoot>
  1332. <tr>
  1333. <td><a href="https://en.wikipedia.org/wiki/Page_footer">Footer</a></td>
  1334. <td>
  1335. Multiple <a href="1">links:</a> <a href="2">Only first captured.</a>
  1336. </td>
  1337. </tr>
  1338. </tfoot>
  1339. </table>
  1340. """
  1341. gh_13141_expected = {
  1342. "head_ignore": ["HTTP", "FTP", "Linkless"],
  1343. "head_extract": [
  1344. ("HTTP", None),
  1345. ("FTP", None),
  1346. ("Linkless", "https://en.wiktionary.org/wiki/linkless"),
  1347. ],
  1348. "body_ignore": ["Wikipedia", "SURROUNDING Debian TEXT", "Linkless"],
  1349. "body_extract": [
  1350. ("Wikipedia", "https://en.wikipedia.org/"),
  1351. ("SURROUNDING Debian TEXT", "ftp://ftp.us.debian.org/"),
  1352. ("Linkless", None),
  1353. ],
  1354. "footer_ignore": [
  1355. "Footer",
  1356. "Multiple links: Only first captured.",
  1357. None,
  1358. ],
  1359. "footer_extract": [
  1360. ("Footer", "https://en.wikipedia.org/wiki/Page_footer"),
  1361. ("Multiple links: Only first captured.", "1"),
  1362. None,
  1363. ],
  1364. }
  1365. data_exp = gh_13141_expected["body_ignore"]
  1366. foot_exp = gh_13141_expected["footer_ignore"]
  1367. head_exp = gh_13141_expected["head_ignore"]
  1368. if arg == "all":
  1369. data_exp = gh_13141_expected["body_extract"]
  1370. foot_exp = gh_13141_expected["footer_extract"]
  1371. head_exp = gh_13141_expected["head_extract"]
  1372. elif arg == "body":
  1373. data_exp = gh_13141_expected["body_extract"]
  1374. elif arg == "footer":
  1375. foot_exp = gh_13141_expected["footer_extract"]
  1376. elif arg == "header":
  1377. head_exp = gh_13141_expected["head_extract"]
  1378. result = flavor_read_html(StringIO(gh_13141_data), extract_links=arg)[0]
  1379. expected = DataFrame([data_exp, foot_exp], columns=head_exp)
  1380. expected = expected.fillna(np.nan)
  1381. tm.assert_frame_equal(result, expected)
  1382. def test_extract_links_bad(self, spam_data):
  1383. msg = (
  1384. "`extract_links` must be one of "
  1385. '{None, "header", "footer", "body", "all"}, got "incorrect"'
  1386. )
  1387. with pytest.raises(ValueError, match=msg):
  1388. read_html(spam_data, extract_links="incorrect")
  1389. def test_extract_links_all_no_header(self, flavor_read_html):
  1390. # GH 48316
  1391. data = """
  1392. <table>
  1393. <tr>
  1394. <td>
  1395. <a href='https://google.com'>Google.com</a>
  1396. </td>
  1397. </tr>
  1398. </table>
  1399. """
  1400. result = flavor_read_html(StringIO(data), extract_links="all")[0]
  1401. expected = DataFrame([[("Google.com", "https://google.com")]])
  1402. tm.assert_frame_equal(result, expected)
  1403. def test_invalid_dtype_backend(self):
  1404. msg = (
  1405. "dtype_backend numpy is invalid, only 'numpy_nullable' and "
  1406. "'pyarrow' are allowed."
  1407. )
  1408. with pytest.raises(ValueError, match=msg):
  1409. read_html("test", dtype_backend="numpy")
  1410. def test_style_tag(self, flavor_read_html):
  1411. # GH 48316
  1412. data = """
  1413. <table>
  1414. <tr>
  1415. <th>
  1416. <style>.style</style>
  1417. A
  1418. </th>
  1419. <th>B</th>
  1420. </tr>
  1421. <tr>
  1422. <td>A1</td>
  1423. <td>B1</td>
  1424. </tr>
  1425. <tr>
  1426. <td>A2</td>
  1427. <td>B2</td>
  1428. </tr>
  1429. </table>
  1430. """
  1431. result = flavor_read_html(StringIO(data))[0]
  1432. expected = DataFrame(data=[["A1", "B1"], ["A2", "B2"]], columns=["A", "B"])
  1433. tm.assert_frame_equal(result, expected)